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>
<html>
    <head>
        <title>{{ title }}</title>
    </head>
    <body>
        <h1>{{ title }}</h1>
        <div>
            <p>{{ static_content }}</p>
            <ul>
            {{#urls}}
                <li>Listed: {{ url }}</li>
            {{/urls}}
            </ul>
        </div>
    </body>
</html>

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

to_html do
    {:ok, template} = File.read(‘templates/list_template.mustache’)
    ctx = [
        title: 'Mustache lists with Elixir',
        static_content: 'The following items are from the supplied list:',
        urls: [
            [url: 'http://www.distortedthinking.agency'],
            [url: 'http://pragprog.com'],
            [url: 'http://www.whitemonkeysoftware.co.uk'],
        ]
     ]
     Mustache.render(template, ctx)
end

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