Magento2 How to add dynamic content on CMS pages

Magento2 How to add dynamic content on CMS pages

Sometimes we need to add a dynamic content to the CMS pages. We can use 2 possible ways to achieve that:

  1. Calling a custom phtml file directly from CMS page.
  2. Using a layout xml.

1. Calling a custom phtml file from CMS page

The smart way of adding dynamic content is by calling a phtml directly inside a CMS page. It is similar to creating block inside layout files, but this will be specific to a specific CMS page.

{{block class="Magento\Framework\View\Element\Template" template="Vendor_Module::your-custom-phtml.phtml"}}

We can also specify additional attribute, like cacheable or name

{{block cacheable="false" class="Magento\Framework\View\Element\Template" name="your_custom_phtml" template="Vendor_Module::your-custom-phtml.phtml"}}

2. Using a layout xml

The other way of adding a dynamic content is by calling phtml from cms_page_view.xml file. You can choose this way if you want to call your template inside all CMS pages.

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="content">
            <block class="Magento\Framework\View\Element\Template" template="Vendor_Module::your-custom-phtml.phtml" 
                   name="your_custom_phtml" />
        </referenceBlock>
    </body>
</page>

Now create the template file inside your template directory. Vendor/Module/view/frontend/templates/your-custom-phtml.phtml.

Inside the template we will display a greeting message if customer is logged in.

<?php
/**
 * @var \Magento\Framework\View\Element\Template $block
 */
?>

<?php
$context = \Magento\Framework\App\ObjectManager::getInstance()
    ->get('Magento\Framework\App\Http\Context');
$isLoggedIn = $context->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH);
$greetingMessage = 'Please <a href="' . $block->getBaseUrl() . 'customer/account/login">login to your account</a> to get greeting message.';
if($isLoggedIn) {
    $greetingMessage = "Greetings Valued customer!";
}
?>
<h1><?= $greetingMessage ?></h1>

Output for guest user:

Login to your account output message

For logged in customer:

Logged in user Greetings
Logged in user Greetings

Leave a Reply

Your email address will not be published. Required fields are marked *