Using erlydtl with Cowboy

Erlydtl seems to be the most popular Erlang templating library, and using it with Cowboy is fairly simple; but doesn’t seem to be terribly well documented.

As always, I’m assuming you’re using erlang.mk and know how to set up a Cowboy project. First, you need to add erlydtl as a dependency in your Makefile:

PROJECT = cowboy_stormpath
DEPS = cowboy erlydtl
include erlang.mk

and as a dependency in your .app.src:

{application, cowboy_erlydtl, [
    {description, ""},
    {vsn, "0.1.0"},
    {id, "git"},
    {modules, []},
    {registered, []},
    {applications, [
        kernel,
        stdlib,
        cowboy,
        erlydtl
    ]},
    {mod, {cowboy_erlydtl_app, []}},
    {env, []}
]}.

Next, create a folder called “templates” in your project root, any .dtl files in here will be compiled when you run “make app”:

<html><body>Your favourite Smurf is {{ smurf_name }}.</body></html>

If you look in ebin/ you should see a file named smurfin_dtl.beam (or whatever), this is the compiled version of your template. Finally, you need a handler to render the template:

-module(smurf_handler).
-behaviour(cowboy_http_handler).

-export([init/3]).
-export([handle/2]).
-export([terminate/3]).

-record(state, {}).

init(_, Req, _Opts) ->
    {ok, Req, #state{}}.

handle(Req, State=#state{}) ->
    {ok, Body} = smurfin_dtl:render([{smurf_name, "Smurfette"}]),
    {ok, Req2} = cowboy_req:reply(200, [{<<"content-type">>, <<"text/html">>}], Body, Req),
    {ok, Req2, State}.

terminate(_Reason, _Req, _State) ->
    ok.

and add a route:

    Dispatch = cowboy_router:compile([
        {'_', [
            {"/smurfin", smurf_handler, []}
        ]}
    ]),

et voila, you’ve rendered your first template!

Advertisements

One thought on “Using erlydtl with Cowboy

  1. Zhijun Wang March 2, 2015 / 5:37 am

    make app and smurfin_dtl:render
    the two command is what i was looking for,
    very informative post, thank you very much

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s