Phoenix templates: Yup, they are just functions

I’ve heard Chris McCord say that Phoenix’s templates are fast because they are just functions.

Even though I find that quite interesting I never questioned how this is achieved.

It was until last weekend that I decided to read randomly from the Elixir documentation, fueled by some post-elixirconf excitement.

I ended up reading about EEx templates.

If you have used Phoenix before, you should recognize EEx as the templating system that Phoenix uses.

What you might not know is that EEx is part of the standard library of Elixir and that it is capable of compiling a template into a function.

Why would you care? First, because its awesome. Second, because it gives you the power to easily separate logic from presentation in whatever you are doing quite easily.

example, create a CSV report

Lets create a simple mix project that spits out a CSV file.

mix new example
cd example

Then, edit the file lib/example.ex. We are going to require EEX and then point to to a file that will be compiled into a function.

defmodule Example do

  require EEx

  # this is where the magic happens. EEx will read the template `lib/sample.eex`
  # and define (def) a function called `whatever_name` that expects
  # one parameter called list, that parameter will be available to us in
  # the template.
  EEx.function_from_file :def, :whatever_name, "lib/sample.eex", [:list]

  def run do
    # we call our magically created function with some data
    IO.puts whatever_name(a: 1, b: 2, c: 3, d: 4)
  end
end

And now, we edit the lib/sample.eex file, which will contain the code that will generate our very dummy CSV file.

<%= for {k, v} <- list  do %><%= k %>,<%= v %>
<% end %>

We run it like so:

mix run -e Example.run

and you should see the following output:

Compiling 1 file (.ex)
a,1
b,2
c,3
d,4

Like promised, they are, indeed, just functions.