Hi guys,
Today we continue to discover more Magento 2 tutorials on making the block visibility dynamic that is quite essential for adding module blocks to the layout.
GET MORE KNOWLEDGE about Referencing a CMS block in Magento 2 to add it into a position of a page or multiple pages!
As you already know, we can configure any block to display or not based on the Magento / Config / Model / Config / Source / Yesno configuration field by using the ifconfig argument. For the value, we can use XPath for the required field:
<block class="Namespace\Module\Block\Type" name="block.example" ifconfig="my/yesno/field">
...
</block>
For example: You check demo in the core contact module using ifconfig:
vendor/magento/module-contact/view/frontend/layout/default.xml
<referenceBlock name="footer_links">
<block class="Magento\Framework\View\Element\Html\Link\Current"
ifconfig="contact/contact/enabled" name="contact-us-link">
<arguments>
<argument name="label" xsi:type="string"
translate="true">Contact Us</argument>
<argument name="path" xsi:type="string">contact</argument>
</arguments>
</block>
</referenceBlock>
We also adjust the visibility by ACL Resource. Although it is primarily used in the admin area, the similar approach works for the frontend of the website.
<block class="Namespace\Module\Block\Type" name="block.example"
aclResource="Vendor_ModuleName::acl_name">
<!-- ... -->
</block>