1

I'm currently adding a body class in my module's default.xml but I can't (to my knowledge) conditionally add it within the XML file based on the module's configuration values. See this question - Conditionally add CSS class to body tag where they show that attributes don't support ifconfig.

/view/frontend/layout/default.xml

<body>
    <attribute name="class" value="mageziner-loading" />
</body>

However, I do NOT want this body css class to be added if the module is disabled such as ifconfig="design/mageziner/enable_frontend" AND when a config value is not equal to a specific value.

I'm currently conditionally loading a template by checking for specific config values within the block class:

default.xml

<referenceContainer name="before.body.end">
    <block class="Gil\Mageziner\Block\Mageziner" name="gil_mageziner_sidebar"  template="Gil_Mageziner::sidebar.phtml"/>
</referenceContainer>

module's block:

protected function _toHtml()
{
    if ($this->getConfig('design/mageziner/enable_frontend') && $this->withinSelectedGroup()) {
        return parent::_toHtml();
    }

    return '';
}

withinSelectedGroup() inside module's block

 /**
 *
 * Does the current user match the whitelisted groups? (Logged out users have a group ID of 0)
 *
 * @return bool
 */
protected function withinSelectedGroup() {
    $customerGroupId = $this->_customerSession->getCustomerGroupId();
    $whitelistedGroupIds = explode(",", $this->getConfig('design/mageziner/customer_group')); // string is returned with multiple group IDs seperated by a ','

    if (in_array($customerGroupId, $whitelistedGroupIds)) {
        return true;
    }

    return false;
}

of key interested is, $this->withinSelectedGroup() which if it returns false does not render the sidebar.phtml template. How would I add a body class if that value is returned as true?

Also, would it be possible to also conditionally load CSS/JS based on that value? Currently I always load the asset files which is NOT ideal.

Thanks for any help/insight. I've been looking around and can't find any solutions for Magento 2.

Your Answer

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

Browse other questions tagged or ask your own question.