Jinja (Jinja v0.0.1)

View Source

Jinja is a fast, expressive, extensible templating engine written in Python.

This library provides a public API for working with Jinja templates in Elixir. This is not a port of Jinja, but rather a wrapper that runs using Pythonx.

See https://jinja.palletsprojects.com/en/stable/templates/ for a guide on template syntax.

Usage

Add Jinja to your application supervision tree:

children = [
  Jinja,
  ...
]

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"}

# `load_template/2` is unavailable for loader: :path
Jinja.load_template("bye", "...") # => {:error, "loading templates at runtime is only supported for loader: :dict"}

Summary

Functions

Returns a specification to start this module under a supervisor.

Loads a template with the given name and source.

Renders a template string with given assigns.

Renders a previously loaded template with given assigns.

Functions

child_spec(init_arg)

Returns a specification to start this module under a supervisor.

See Supervisor.

load_template(name, source)

@spec load_template(String.t(), String.t()) :: :ok | {:error, term()}
@spec load_template(String.t(), map()) :: {:ok, String.t()} | {:error, term()}

Loads a template with the given name and source.

iex> Jinja.load_template("page", """
<html><body>{% block body %}{% endblock %}</body></html>
""")
:ok

iex> Jinja.load_template("post", """
{% extends "page" %}
{% block body %}
  {{ title }}
{% endblock %}
""")
:ok

render_string(template, assigns \\ %{})

@spec render_string(String.t(), map()) :: {:ok, String.t()} | {:error, term()}

Renders a template string with given assigns.

iex> Jinja.render_string("<h1>hewwo {{ name }}</h1>", %{"name" => "world"})
{:ok, "<h1>hewwo world</h1>"}

render_template(name, assigns \\ %{})

Renders a previously loaded template with given assigns.

iex> Jinja.render_template("post", %{title: "hewwo world"})
{:ok, "<html><body>hewwo world</body></html>"}