Back to Top

How to Pass Dynamic Data in Email Template – Magento2

Updated 28 February 2023

In this blog we will see how to pass dynamic or dependent data to email templates in Magento2. Some times we need to pass dynamic data to email templates and we can not do this using template variables because we don’t know how many variables we need to create or send.

For example – Order items in order email or other order related emails depend upon the order and its totally dynamic.

So we can not pass this data using variables in email template. For this kind of situations Magento provides a method by which we can call phtml file in email templates.

We can achieve this by using custom handles.

To use custom handles in email templates –

Searching for an experienced
Magento 2 Company ?
Find out More
  • Create Layout Handle
  • Create Template File
  • Call Layout Handle In Email Template File

Create Layout Handle

First of all create a xml file in frontend layout folder. i am creating a email_template.xml. you can choose any name for layout.

<?xml version="1.0"?>
<page xmlns:xsi="" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd" label="Email Items" design_abstraction="custom">
        <block class="Magento\Framework\View\Element\Template" name="email.items" template="Vendor_ModuleName::email_items.phtml"/>

Create Template File

Create template file email_items.phtml. You can write code according to your need in this file.

    echo "This data is dynamic data and can be changed according to need.";
    // You can print data accoding to your need. 
    // You can also get the parameters on this file.

You can fetch parameter and use them in this file. For example – you can get id or any other parameter from request object and perform operations using the data.

Call Layout Handle In Email Template File

Finally you need to use the layout handle in email template file.

{{layout area="frontend" handle="email_template"}}


email_template is the name of xml file you created at first step.

That’s all for today. I hope this blog will help you.
If you have any issue or query, comment below.

. . .

Leave a Comment

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

Be the first to comment.

Back to Top

Message Sent!

If you have more details or questions, you can reply to the received confirmation email.

Back to Home