Back to Top

How to apply a transformation to an email template from an external module

Updated 5 April 2024

In this blog, we are going to learn, How to apply a transformation to an email template from an external module. We can apply our own transformation to the content from our module.

We can add multiple content transformation. To implement this feature we require you to know How to add email layouts in a theme. After adding a customized layout to a theme. Here is an example of an email layout using the TransformationInterface.

The Transformation Interface is a powerful and handy way to modify our email template’s design easily. Let us check out the interface details:

<?php
namespace PrestaShop\PrestaShop\Core\MailTemplate\Transformation;

interface TransformationInterface
{
    /**
     * @param string $templateContent
     * @param array $templateVariables
     *
     * @return string
     */
    public function apply($templateContent, array $templateVariables);

    /**
     * Returns the type of templates this transformation is associated with,
     * either html or txt, so that the renderer knows if it has to be applied
     * or not
     *
     * @return string
     */
    public function getType();

    /**
     * @param LanguageInterface $language
     *
     * @return $this
     */
    public function setLanguage(LanguageInterface $language);
}

The apply method is the most important, it receives the rendered layout content as a string, then we can perform the string replacement or even DOM (Document Object Model) manipulation as long as we return the whole template as a string (if we do not want modify it, we can simply return the string un modified).

The getType method is used to filter transformations (a transformation is only applicable) to one type, as for the setLanguage method it will allow you to know the language used in this generation which is handy if you need to add localized texts or images.

Searching for an experienced
Prestashop Company ?
Find out More

Let’s start,

Layout

For this example, we will use the same layout we use in How to add email layouts in a theme.

{# modules/WkTestModule/mails/layout/custom_classic_webkul_layout.html.twig #}

{# You can use the theme layout (if present) to extend it easily #}
{% extends '@MailThemes/classic/components/layout.html.twig' %}

{% block content %}
<tr>
  <td class="space_footer">&nbsp;</td>
</tr>
<tr>
  <td class="space_footer">
    <table width="100%">
      <tr>
        <td align="center" class="titleblock">
          <font size="2" face="{{ languageDefaultFont }}Open-sans, sans-serif" color="#555454">
            <strong class="title">{{ 'This is an example mail template from my test module for classic theme'|trans({}, 'EmailsBody', locale)|raw }}</strong>
          </font>
        </td>
      </tr>
      <tr>
        <td align="center" class="titleblock">
          <font size="2" face="{{ languageDefaultFont }}Open-sans, sans-serif" color="#555454">
            <span class="wk_subtitle">{{ customizedMessage }}</span>
          </font>
        </td>
      </tr>
      <tr>
        <td class="space_footer">&nbsp;</td>
      </tr>
    </table>
  </td>
</tr>
{% endblock %}
{% block footer %}
<tr>
  <td class="space_footer">&nbsp;</td>
</tr>
<tr>
  <td class="footer" style="border-top: 4px solid #333333">
    <span>{{ '<a href="{shop_url}">{shop_name}</a> created by <a
        href="https://webkul.com/">Webkul</a>'|trans({'{prestashop_url}':
      'https://www.prestashop.com/?utm_source=marchandprestashop&utm_medium=e-mail&utm_campaign=footer_1-7'},
      'Emails.Body', locale)|raw }}</span>
  </td>
</tr>
{% endblock footer %}

Note: The <span class="wk_subtitle"> that contains the custom message, we will use a CSS selector for our content transformation.

The Transformation class

In this example, we are going to create a class implementing the TransformationInterface and define its needed methods. Its purpose is to change the color of all the <span> tags with the wk_subtitle class.

<?php
namespace PrestaShop\Module\WkTestModule\MailTemplate\Transformation;

use PrestaShop\PrestaShop\Core\Exception\InvalidArgumentException;
use PrestaShop\PrestaShop\Core\MailTemplate\MailTemplateInterface;
use PrestaShop\PrestaShop\Core\MailTemplate\Transformation\AbstractTransformation;
use Symfony\Component\DomCrawler\Crawler;
use DOMElement;

/**
 * Class CustomMessageColorTransformation adds the custom color to all spans
 * with class subtitle.
 */
class CustomMessageColorTransformation extends AbstractTransformation
{
    /** @var string */
    private $customColor;

    /**
     * @param string $customColor
     * @throws InvalidArgumentException
     */
    public function __construct($customColor)
    {
        parent::__construct(MailTemplateInterface::HTML_TYPE);
        $this->customColor = $customColor;
    }

    /**
     * @inheritDoc
     */
    public function apply($templateContent, array $templateVariables)
    {
        $crawler = new Crawler($templateContent);
        $customSpans = $crawler->filter('span[class="wk_subtitle"]');
        /** @var DOMElement $customSpan */
        foreach ($customSpans as $customSpan) {
            $customSpan->setAttribute('style', sprintf('color: %s;', $this->customColor));
        }

        return $crawler->html();
    }
}

Using the hook

Now we need to add our transformation for this mentioned layout, in order to do this we will use the MailTemplateRendererInterface::GET_MAIL_LAYOUT_TRANSFORMATIONS  hook.
It derive the following hook name “actionGetMailLayoutTransformations”

Now, we are going to define this hook in our modules main file.

<?php
use PrestaShop\PrestaShop\Core\MailTemplate\MailTemplateInterface;
use PrestaShop\PrestaShop\Core\MailTemplate\MailTemplateRendererInterface;
use PrestaShop\PrestaShop\Core\MailTemplate\Layout\LayoutInterface;
use PrestaShop\PrestaShop\Core\MailTemplate\Transformation\TransformationCollectionInterface;
use PrestaShop\Module\WkTestModule\MailTemplate\Transformation\CustomMessageColorTransformation;

class WkTestModule extends Module 
{
   public function install() 
   {
        return parent::install()
            // This class constant contains 'actionGetMailLayoutTransformations'
            && $this->registerHook(MailTemplateRendererInterface::GET_MAIL_LAYOUT_TRANSFORMATIONS)
        ;
    }
    
    public function uninstall() 
    {
        return parent::uninstall()
            && $this->unregisterHook(MailTemplateRendererInterface::GET_MAIL_LAYOUT_TRANSFORMATIONS)
        ;        
    }
    
    public function enable() 
    {
        return parent::enable()
            && $this->registerHook(MailTemplateRendererInterface::GET_MAIL_LAYOUT_TRANSFORMATIONS)
        ;
    }
    
    public function disable() 
    {
        return parent::disable()
            && $this->unregisterHook(MailTemplateRendererInterface::GET_MAIL_LAYOUT_TRANSFORMATIONS)
        ;        
    }
    
    /**
     * @param array $hookParams
     */
    public function hookActionGetMailLayoutTransformations(array $hookParams)
    {
        if (!isset($hookParams['templateType']) ||
            MailTemplateInterface::HTML_TYPE !== $hookParams['templateType'] ||
            !isset($hookParams['mailLayout']) ||
            !isset($hookParams['layoutTransformations'])) {
            return;
        }

        /** @var LayoutInterface $mailLayout */
        $mailLayout = $hookParams['mailLayout'];
        if ($mailLayout->getModuleName() != $this->name) {
            return;
        }

        /** @var TransformationCollectionInterface $transformations */
        $transformations = $hookParams['layoutTransformations'];
        $transformations->add(new CustomMessageColorTransformation('#0000FF'));
    }
}

We can check the result. To check the we need to go to the “Design > Email Theme” page and preview our layout. We will see that our message has now changed its color.

Transformation

That’s all about this blog.

If any issues or doubts in the above step, please feel free to let us know in the comment section.

We would be happy to help.

You can also explore our PrestaShop Development Services and a large range of quality PrestaShop Modules.

For any doubt contact us at [email protected].

. . .

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