20
19

More than 5 years have passed since last update.

Phoenixに自作のテンプレートエンジンを追加する

Posted at

nantoka.foo を踏んだら発火するテンプレートエンジンを自分で実装したいと思った。

やり方

Phoenix.Template.Engine のbehaviour を備えて compile/2 を実装する。

defmodule FooEngine {
  @behaviour Phoenix.Template.Engine
  def compile(_path, _name) do
      {:safe, "Foo"}
  end
}

config/config.ex に追記

config :phoenix, :template_engines,
  foo: FooEngine

これで拡張子fooを踏んだら何でもFooを返す

web/templates/nantoka.foo

仕組み

基本的にはpathnameみてFile.read! してコンパイラ切り替えたりする。
calliope っていう elixirでのhaml 実装があって、 これを使ったphoenix-hamlがある

nurugger07/calliope

chrismccord/phoenix_haml

たとえば phoenix_haml の Engineの定義はこうなってる

defmodule PhoenixHaml.Engine do
  @behaviour Phoenix.Template.Engine

  @doc """
  Precompiles the String file_path into a function defintion, using Calliope engine
  """
  def compile(path, _name) do
    path
    |> read!
    |> EEx.compile_string(engine: Phoenix.HTML.Engine, file: path, line: 1)
  end

  defp read!(file_path) do
    file_path |> File.read! |> Calliope.Render.precompile
  end
end

学びがあった

20
19
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
20
19