Jinja - Elixir API for Jinja templates using Pythonx

Renders Jinja templates, either from disk or defined at runtime, with support for all native Jinja features (including extends).

It does this by wrapping the real Jinja library, running in an embedded Python interpreter, inside a GenServer with a nice Elixir API. It uses Pythonx for this.

You start it by adding Jinja to your application supervision tree. There are two loaders:

The default loader is :dict. This allows you to register templates at runtime, for the lifetime of your application. Templates can be loaded and rendered as such:

Jinja.load_template("hello", "hewwo {{ name }}") # => :ok
Jinja.render_template("hello", %{name: "Robin"}) # => {:ok, "hewwo Robin"}

The :path loader allows you to specify a directory on disk to load templates from. When configured, the load_template/2 function will be unavailable.

children = [
  {Jinja,
    loader: :path,
    from: Application.app_dir(:your_app, ~w(lib your_app_web templates))
  }
]

# Loads template from lib/your_app_web/templates/hello.html
Jinja.render_template("hello.html", %{name: "Robin"}) # => {:ok, "hewwo Robin"}

The library is available on GitHub and Codeberg:

Let me know what you think!

6 Likes

First, why? Second, what happens when an overwhelmingly many requests arrive and each and every one ends up calling the Jinja process?

2 Likes

First, why?

I wanted to use Jinja templates in Elixir for a building a CMS. Jinja is well-known, supported in other languages as well and makes it a good fit for a headless CMS. Something like HEEx cannot be consumed by other programs/frontends and I am not a huge fan of Liquid.

Second, what happens when an overwhelmingly many requests arrive and each and every one ends up calling the Jinja process?

Pythonx runs a single interpreter under the hood (it does not launch a new interpreter instance for every request made). You can always create multiple instances if that works better for your architecture.

did you try erlydtl.
its been around for while and has a lot of features.