Rendering MJML in PHP

Quentin Ferrer
2 min readApr 3, 2020

--

When I discovered MJML, I was happy to find a framework that helps me code responsive email. But I’m a PHP developer and I want to use it in my application. This is why I created a simple library to make easier the integration of MJML for all those who want to create responsive email in PHP.

Installation

composer require qferr/mjml-php

Rendering templates

There are two ways for rendering MJML in PHP:

  • using MJML API, if you don’t want to install anything. It’s free to use !
  • using MJML library, if you don’t want to depend of an external service.

Rendering from the API

You have to provide the credentials to access of the MJML API:

  • appId: the application ID.
  • secretKey: the secret key.
<?php
require_once 'vendor/autoload.php';
use \Qferrer\Mjml\Renderer\ApiRenderer,// Credentials
$appId = 'abcdef-1234-5678-ghijkl';
$secretKey = 'ghijkl-5678-1234-abcdef';

$renderer = new ApiRenderer($appId, $secretKey);

$html = $renderer->render('
<mjml>
<mj-body>
<mj-section>
<mj-column>
<mj-text>Hello world</mj-text>
</mj-column>
</mj-section>
</mj-body>
</mjml>
');

Rendering from the library

You need to install the library:

npm install mjml

and provide the location of the MJML binary:

<?php
require_once 'vendor/autoload.php';
use \Qferrer\Mjml\Renderer\BinaryRenderer;$renderer = BinaryRenderer(__DIR__ . '/node_modules/.bin/mjml');

$html = $renderer->render('
<mjml>
<mj-body>
<mj-section>
<mj-column>
<mj-text>Hello world</mj-text>
</mj-column>
</mj-section>
</mj-body>
</mjml>
');

That’s all ! You are ready to code and render MJML in HTML responsive in PHP.

Bonus: Creating your own renderer

Of course, you can create your own renderer by using the RendererInterface .

<?phpnamespace App\Renderer;

use \Qferrer\Mjml\Renderer\RendererInterface;

class CustomRenderer implements RendererInterface
{
public function render(string $content) : string
{
// Implement your logic
}
}

--

--

Quentin Ferrer
Quentin Ferrer

Written by Quentin Ferrer

I’m a french web developer. I develop in PHP with the popular Symfony framework.

No responses yet