Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Integrate mjml-python? #184

Open
blopker opened this issue Oct 25, 2023 · 3 comments
Open

Integrate mjml-python? #184

blopker opened this issue Oct 25, 2023 · 3 comments

Comments

@blopker
Copy link

blopker commented Oct 25, 2023

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
Copy link
Author

blopker commented Oct 26, 2023

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
Copy link
Owner

@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
Copy link

aplex commented Jan 26, 2024

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants