2

How to add any class in body or category-view div on category page if current category don't have image assigned.

Having following top container part in the catalog_category_view.xml file.

<referenceContainer name="columns.top">
            <container name="category.view.container" htmlTag="div" htmlClass="category-view" after="-">
                <block class="Magento\Catalog\Block\Category\View" name="category.image" template="Magento_Catalog::category/image.phtml"/>
                <block class="Magento\Catalog\Block\Category\View" name="category.description" template="Magento_Catalog::category/description.phtml"/>
                <block class="Magento\Catalog\Block\Category\View" name="category.cms" template="Magento_Catalog::category/cms.phtml"/>
            </container>
        </referenceContainer>
2
  • So You want to add class to body if category has no image ? – anonymous Dec 20 '18 at 5:02
  • yes within body or next to category-view class – MageSoftech Dec 24 '18 at 4:04
1

Override Image.phtml file in your theme.

File Path: /app/design/frontend/Vendor_Name/Theme_Name/Magento_Catalog/templates/category/image.phtml

<?php

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
// @codingStandardsIgnoreFile
?>
<?php

/**
 * Category view template
 *
 * @var $block \Magento\Catalog\Block\Category\View
 */
?>
<?php

$_helper = $this->helper('Magento\Catalog\Helper\Output');
$_category = $block->getCurrentCategory();
$_imgHtml = '';
if ($_imgUrl = $_category->getImageUrl()) {
    $_imgHtml = '<div class="category-image"><img src="' . $_imgUrl . '" alt="' . $block->escapeHtml($_category->getName()) . '" title="' . $block->escapeHtml($_category->getName()) . '" class="image" /></div>';
    $_imgHtml = $_helper->categoryAttribute($_category, $_imgHtml, 'image');
    /* @escapeNotVerified */ echo $_imgHtml;
} else {
    ?>
    <script>
    require([
        'jquery'
    ], function ($) {
       $( document ).ready(function() {
            $('body').addClass('newClass');
        });
    });
</script>


  <?php
}
?>
3
  • Thanks apart from script any other way to call this. – MageSoftech Dec 24 '18 at 4:05
  • 1
    You can add class like, In your Layout File : <body> <attribute name="class" value="my-css-class"/> But you need condition based add class, So i think this is the only way. – Nauman m. Mansuri Dec 24 '18 at 5:39
  • Thanks, this was a good trick to be able to hide some bundle template elements – iphigenie Jul 3 '20 at 15:16

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.