Templates in database

Does anyone have experience, examples, blog posts or etc regarding rendering (liquid) templates from the database in Phoenix?

This is what I got so far:

defmodule Frontend.LiquidView do
  @moduledoc false

  alias Liquid.Template

  def render_liquid(template, assigns) when is_binary(template) and is_map(assigns) do
    template
    |> Template.parse()
    |> Template.render(assigns)
  end
end
defmodule Frontend.LayoutView do
  @moduledoc false

  use Frontend.Web, :liquid_view

  def render("app.html", assigns) do
    template = "<!doctype><html>{{content}}</html>" # for the sake of the example, this will come from the db

    content =
      assigns.view_template
      |> assigns.view_module.render(assigns)

    case render_liquid(template, %{"content" => content}) do
      {:ok, html, _} -> {:safe, html}
      _              -> "Error rendering template"
    end
  end
end
defmodule Frontend.StorefrontView do
  @moduledoc false

  use Frontend.Web, :liquid_view

  def render("index.html", assigns) when is_map(assigns) do
    template = "{% assign hello='Hello' %}<strong>{{ hello }}</strong>, {{world}}!"

    case render_liquid(template, %{"world" => assigns.world}) do
      {:ok, html, _} -> html
      _              -> "Error rendering template"
    end
  end
end
4 Likes

What exactly are you stuck on? I have not done it with Phoenix, but I’ve created database-backed Liquid template rendering engines twice using Rails.

2 Likes

Not really stuck, just wondering if there was a better way of doing it. I’ve done it in Rails many times as well.

Currently looking into creating a DB FileSystem.

1 Like