The way to make it different from others is to customize the way you love & your viewers want to see. Having Magento as open source CMS you are free to personalize and develop the way you love by installing the theme and extensions. And this theme is made up of several elements like code, blocks, widgets, media and so on. But when it comes to the static block, it is helpful in several ways to display text, sliders, product carousels, ads as well as chunks of HTML/JS/CSS code.
These Magento CMS Blocks are pretty useful when we want to make manipulation of content easier instead of having a static one. Also, changing block content can take just a few minutes and can save tons of time Instead of looking into thousands of line code. You can consider this example to show discount tables for different purchase total dynamically. To do the same, first we need to create a block file at the following location.
app\code\Vendor\Extension\Block\Cmsblock.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | class Cmsblock { protected $cmsblock; public function __construct(\Magento\Cms\Block\Block $cmsblock) { $this->cmsblock = $cmsblock; } public function Fetchcmsblockdata() { $cmsblockdata = $this->cmsblock->setBlockId('block_identifier')->toHtml(); return $cmsblockdata; } } |
Note: Make sure you have replaced ‘block_identifier‘ with your CMS block identifier.
Now to use these block class into our Magento template file, we need to specify the following code in our “vendor_extension_index.xml“.
app\code\Vendor\Extension\view\frontend\layout\vendor_extension_index.xml
1 2 3 4 5 6 7 8 | <?xml version="1.0"?> <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <body> <referenceContainer name="content"> <block class="Vendor\Extension\Block\Cmsblock " template="Vendor_ Extension::cmsdata.phtml" name="mycmsdata"/> </referenceContainer> </body> </page> |
Lastly, we need to create “cmsdata.phtml” file at below location to fetch block data.
app\code\Vendor\Extension\view\frontend\templates\cmsdata.phtml
1 | <?php echo $block->Fetchcmsblockdata(); ?> |
If you need help regarding the above code? Don’t forget to leave a comment and if this found it helpful smash that stars.
Happy Coding!