1

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

1
  • Although the ans provided by me on the link that you shared is definitely sufficient to perform the needed. But if you are still unable to do so I may suggest having a look at default coding, look how magento shows Customer name in top header only for logged in customer, hope that may help you. – Narendra Vyas Jul 30 '19 at 0:01
1

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.

2

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>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.