qferr/mjml-twig

There is no license information available for the latest version (2.0.1) of this package.

Twig extension that provides a filter that processes a mjml email template

2.0.1 2022-05-27 08:43 UTC

This package is auto-updated.

Last update: 2024-04-27 12:49:03 UTC


README

This package is a Twig extension that provides the following:

  • mjml_to_html filter: processes a mjml email template.
{% apply mjml_to_html %}
<mjml>
    <mj-body>
        <mj-section>
            <mj-column>
                <mj-text>Hello {{ username }}</mj-text>
            </mj-column>
        </mj-section>
    </mj-body>
</mjml>
{% endapply %}

Because we have two ways for rendering MJML to HML, the extension depends on a renderer:

  • BinaryRenderer: using the MJML library. You will have to provide the location of the MJML binary. Don’t forget to install it with the Node package manager.
  • ApiRenderer: using the MJML API. Nothing to install. You will have to provide the credentials to access of the API.

Thanks to the library MJML in PHP for make easier the integration of MJML in PHP. Read the article Rendering MJML in PHP for more informations.

Installation

composer require qferr/mjml-twig

Usage

<?php
require_once 'vendor/autoload.php';

use \Qferrer\Mjml\Renderer\ApiRenderer;
use \Qferrer\Mjml\Renderer\BinaryRenderer;
use \Qferrer\Mjml\Twig\MjmlExtension;

$loader = new \Twig\Loader\FilesystemLoader(__DIR__ . '/templates');
$twig = new \Twig\Environment($loader);

$renderer = new BinaryRenderer(__DIR__ . '/node_modules/.bin/mjml');
// $api = new \Qferrer\Mjml\Http\CurlApi('my-app-id','my-secret-key');
// $renderer = new \Qferrer\Mjml\Renderer\ApiRenderer($api);
$twig->addExtension(new MjmlExtension($renderer));

$html = $twig->render('newsletter.mjml.twig', [
    'username' => 'Quentin'
]);

You can now start using MJML in any Twig template.

Integrating in Symfony

Register the MJML extension as a service and tag it with twig.extension.

# config/services.yaml
services:
  # Qferrer\Mjml\Http\CurlApi:
  #  arguments:
  #     - '%env(MJML_APP_ID)%'
  #     - '%env(MJML_SECRET_KEY)%'

  # mjml_renderer:
  #  class: Qferrer\Mjml\Renderer\ApiRenderer
  #  arguments:
  #    - '@Qferrer\Mjml\Http\CurlApi'

  mjml_renderer:
    class: Qferrer\Mjml\Renderer\BinaryRenderer
    arguments:
      - '%kernel.project_dir%/node_modules/.bin/mjml'

  Qferrer\Mjml\Twig\MjmlExtension:
    arguments: ['@mjml_renderer']
    tags: ['twig.extension']

Source: Using MJML with Twig