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!