Skip to content

Instantly share code, notes, and snippets.

@cblavier
Created March 5, 2023 18:28
Show Gist options
  • Save cblavier/9e66295b63836f11f76fd4f90a76641f to your computer and use it in GitHub Desktop.
Save cblavier/9e66295b63836f11f76fd4f90a76641f to your computer and use it in GitHub Desktop.
mjml.ex
defmodule Readable.Emails.MJML do
@external_resource __DIR__
def mjml_template(path) do
template = path |> Path.expand(__DIR__) |> File.read!()
{:ok, html} =
~r|<mj-include\s+path="([^"]*)"\s+/>|
|> Regex.scan(template)
|> Enum.map(fn [match, path] ->
{match, path |> Path.expand(__DIR__) |> File.read!()}
end)
|> Enum.reduce(template, fn {match, replacement}, template ->
String.replace(template, match, replacement)
end)
|> Mjml.to_html()
html
|> String.replace("{{", "<%=")
|> String.replace("}}", "%>")
end
defmacro __using__(_) do
for path <- Path.wildcard("#{__DIR__}/*.mjml.eex") do
quote do
@external_resource unquote(path)
def mjml_template(unquote(Path.basename(path, ".mjml.eex")), bindings) do
template = unquote(mjml_template(path))
EEx.eval_string(template, bindings)
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment