All Masterpiece Cakeshop has to do is state that they only provide wedding cakes for weddings that take place at certain churches (and, if they like, synagogues and mosques). Don’t turn people away based on their identities, or the type of wedding they’re conducting. Turn them away based on the place where they are getting married.
That leaves the discrimination up to the religious institution, and churches are allowed to discriminate. They can refuse to host same-sex weddings, interfaith weddings, interracial weddings – whatever. And almost everyone agrees that they should be allowed to do so. Whatever else it means, the First Amendment definitely covers religious institutions’ rights to decide how to practice their religion.
Now, would Masterpiece Cakeshop then be discriminating on the basis of religion? Not if the compromise is done right.