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.
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.
And now, we edit the
lib/sample.eex file, which will contain the code that will generate our very dummy CSV file.
We run it like so:
and you should see the following output:
Like promised, they are, indeed, just functions.