0

I asked a question about adding different class if customer is logged in or not logged : Add CSS class to body if the customer is logged in magento 2 the problem is that i need more explanation to try the solution of pawan so can you please help me and thanks in advance

Developper Magento
  • 1,603
  • 2
  • 14
  • 47

2 Answers2

1

Try this code in your phtml

<?php
 $obm = \Magento\Framework\App\ObjectManager::getInstance();
 $context = $obm->get('Magento\Framework\App\Http\Context');
 $isLoggedIn = $context->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH);
 $customerIsLogging = 0;
?>

<?php if($isLoggedIn): ?>
    $customerIsLogging = 1;
<?php else: ?>
    $customerIsLogging = 0;
<?php endif; ?>


<script type="text/javascript">
    require(['jquery'], function($){
        var isLoggedIn = '<?php echo $customerIsLogging ?>';
        var htmlBody = $("body[data-container='body']");
        if(isLoggedIn == 1){
            htmlBody.addClass("customer-logged-in");
        }else{
            htmlBody.addClass("customer-logged-out");
        }
    });
</script>
Prashant Patel
  • 1,291
  • 11
  • 21
0

This is pawan's solution:

require(['jquery', 'jquery/ui'], function($){
    jQuery(document).ready( function() {
        var isLoggedIn = jQuery('.authorization-link > a').attr('href').indexOf('/login')<0;
        if(isLoggedIn){
            jQuery( ".body" ).addClass( "customer-welcome" );
        }
    });
});

Like above, he checked if the customer is logged in or not by using variable isLoggedIn.

var isLoggedIn = jQuery('.authorization-link > a').attr('href').indexOf('/login')<0;

So, he finds string /login from <a href> tag, if the customer logged in, the variable returns true, otherwise it returns false.

if(isLoggedIn){
     jQuery( ".body" ).addClass( "customer-welcome" );
}

And if it returns true, it will add the class to the body.

Updated

You need to add this js to every pages in frontend like follow:

1) Create js file <vendor>/<module>/view/frontend/web/js/yourjs.js

define(['jquery', 'jquery/ui'], function($){
    $(document).ready( function() {
        var isLoggedIn = $('.authorization-link > a').attr('href').indexOf('/login')<0;
        if(isLoggedIn){
            $(".body").addClass("customer-welcome");
        }
    });
});

2) Declare yourjs.js with requirejs-config.js file

Create requirejs-config.js file in <vendor>/<module>/view/frontend

with content below:

var config = {

// When load 'requirejs' always load the following files also
  deps: [
    "js/yourjs"
  ]
};

3) Create default.xml in <vendor>/<module>/view/frontend/layout

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
        <script src="Vendor_Module::js/yourjs.js"/>
    </head>
</page>
Draze
  • 41
  • 4