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=""
        <referenceBlock name="content">
            <block class="Magento\Framework\View\Element\Template" template="Vendor_Module::your-custom-phtml.phtml" 
                   name="your_custom_phtml" />

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.

 * @var \Magento\Framework\View\Element\Template $block

$context = \Magento\Framework\App\ObjectManager::getInstance()
$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 *