2

It is required to show dynamic javascript userId var in head.additional block if the user is logged in, otherwise null.

So I am injecting my block into default layout handle

    <?xml version="1.0"?>
    <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
        <body>
            <referenceContainer name="head.additional">
                <block class="Test\Test\Block\Head" name="testtest_head" />
            </referenceContainer>
        </body>
    </page>

in the block, I use this code and it works great

class Head extends Template
{
  ...
     protected function _afterToHtml($html)
     {
          return $html. $this->getMyUserIdCode();
     }

}

But when I enable the cache, userId won't refresh even if customer logged in. How can I properly avoid caching in this sutuation ?

1 Answer 1

3

You will have to create helper for this.

File Path:

app/code/Vendor/Module/Helper/Data.php

Code:

<?php

namespace Vendor\Module\Helper;

use Magento\Customer\Model\Context;

class Data extends \Magento\Framework\App\Helper\AbstractHelper
{

    private $httpContext;

    public function __construct(
        \Magento\Framework\App\Helper\Context $context,
        \Magento\Framework\App\Http\Context $httpContext
    ) {
        parent::__construct($context);
        $this->httpContext = $httpContext;
    }

    public function isLoggedIn()    
    {
        $isLoggedIn = $this->httpContext->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH);
        return $isLoggedIn;
    }
}

And this you can reference in your phtml file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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