liminspace / django-mjml

The simplest way to use MJML in Django templates.
MIT License
258 stars 30 forks source link

Integrate mjml-python? #184

Open blopker opened 8 months ago

blopker commented 8 months ago

Hey I love to use this package in our project, but adding Node as a runtime dependency has me a bit scared. Are you interested in adding https://github.com/mgd020/mjml-python as an optional backend? It just wraps https://github.com/jdrouet/mrml (the Rust version of MJML) so no extra runtime dependency needed. Thanks!

blopker commented 8 months ago

For anyone who wants to try this now, I've copied the template tag from this library and copied it into my own project. There's not much to it when you don't have to talk to a separate process:

In templatetags/mjml.py:

from django import template
from mjml import mjml2html

register = template.Library()

class MJMLRenderNode(template.Node):
    def __init__(self, nodelist):
        self.nodelist = nodelist

    def render(self, context) -> str:
        mjml_source = self.nodelist.render(context)
        return mjml_render(mjml_source)

@register.tag
def mjml(parser, token) -> MJMLRenderNode:
    """
    Compile MJML template after render django template.

    Usage:
        {% mjml %}
            .. MJML template code ..
        {% endmjml %}
    """
    nodelist = parser.parse(("endmjml",))
    parser.delete_first_token()
    tokens = token.split_contents()
    if len(tokens) != 1:
        raise template.TemplateSyntaxError("'%r' tag doesn't receive any arguments." % tokens[0])
    return MJMLRenderNode(nodelist)

def mjml_render(mjml_source: str) -> str:
    return mjml2html(mjml_source)
liminspace commented 6 months ago

@blopker I think you can use mjml-python to create a HTTP or a TCP server and use a proper config to use that. It's better to use external service for rendering emails especially if you send a lot of emails. But your idea is a good way to use mjml easier for smaller projects. I'm thinking about supporting customizable classes to make supporting alternative mjml-backends more flexible and allow developers use custom backends without making changes in django-mjml.

aplex commented 5 months ago

Tried @blopker version. Works well so far, and about 100x faster than cmd implementation of django-mjml. 0.006 seconds per render vs 0.9 seconds