Вопрос

Does anyone have an example on how to display a logged in vs logged out message on frontend to customer that's not affected by cache without using the cache=false tag and hole punching the whole page

I'm assuming using knockout / section / customerData / private content somehow.

I've read a lot of tutorials and responses like this https://magento.stackexchange.com/a/261067/70343

But just looking for an example on how to do this

Это было полезно?

Решение

You can just dive in Magento core coding it-self in order to have a better understanding.

Magento shows customer name for logged in customers only and not for guest customers, you may have a look at code responsible for that here:

vendor/magento/module-theme/view/frontend/templates/html/header.phtml

A already created customer section is used in this file have a look here:

<script type="text/x-magento-init">
    {
        "*": {
            "Magento_Ui/js/core/app": {
                "components": {
                    "customer": {
                        "component": "Magento_Customer/js/view/customer"
                    }
                }
            }
        }
    }
    </script>

Then binded by knockout as :

data-bind="scope: 'customer'"

Accessed as :

customer().fullname

Here a pre existing section is been utilized if needed you may create your custom section as well, depending on your need.

Hope that helps.

Другие советы

Narendra certainly pointed me in the right direction.

Here is a complete example.

https://github.com/DominicWatts/CustomerLogin/blob/master/view/frontend/templates/index/index.phtml

<div class="greet welcome" data-bind="scope: 'customer'">
    <!-- ko if: customer().fullname  -->
    <span class="logged-in"
          data-bind="text: new String('<?= $block->escapeHtml(__('Welcome back %1', '%1')) ?>').replace('%1', customer().firstname)">
    </span>
    <!-- /ko -->
    <!-- ko ifnot: customer().fullname  -->
    <span class="not-logged-in"
          data-bind='html:"<?= $block->escapeHtml(__("Please <a href='%1'>login</a>", $block->getUrl('customer/account/login'))) ?>"'>
    </span>
    <!-- /ko -->
</div>
<script type="text/x-magento-init">
{
    "*": {
        "Magento_Ui/js/core/app": {
            "components": {
                "customer": {
                    "component": "Magento_Customer/js/view/customer"
                }
            }
        }
    }
}
</script>
Лицензировано под: CC-BY-SA с атрибуция
Не связан с magento.stackexchange
scroll top