Playing With Fire

Exploring the web one Elixir at a time

Using a template file with Elixir and Ewebmachine

As an extension to the examples presented in my previous post: Basic templating with Elixir-Mustache, I am going to look at separating the HTML from the code.

Usually this is done in the form of templates, and with Elixir and Mustache this is no different.

Taking the last example of the previous post, we will extract the HTML into template file and have Elixir load it prior to render time.

So opening the previous code file, lib/list_template_resource.ex, we extract the HTML that is assigned to the template variable and put it in a separate file. I’m going to create a new directory, templates, to house it.

$ mkdir templates
$ vim templates/list_template.mustache

In this file I cut and paste the HTML from lib/list_template_resource.ex, and for completeness I will also add in the HTML DOCTYPE

<!DOCTYPE html>
        <title>{{ title }}</title>
        <h1>{{ title }}</h1>
            <p>{{ static_content }}</p>
                <li>Listed: {{ url }}</li>

In the code file lib/list_template_resource.ex, change the to_html function to read as follows:

to_html do
    {:ok, template} =‘templates/list_template.mustache’)
    ctx = [
        title: 'Mustache lists with Elixir',
        static_content: 'The following items are from the supplied list:',
        urls: [
            [url: ''],
            [url: ''],
            [url: ''],
     Mustache.render(template, ctx)

Running this via IEx as in the previous example will yield the output as already determined.