Using ErlyWeb templates with MochiWeb

May 05, 2008

Here’s a very simple way to add dynamic templates (views) to a MochiWeb based web front-end. I wouldn’t want to build an entire web application this way, but it’s a quick way to add a simple web interface to your Erlang application.

First I pulled the simple template code from ErlyWeb (erltl.erl) and compiled it with my code.

For this example, here’s a template index.et that shows a list of nodes the Erlang application is connected to.

index.et

<html>
<body>
<h2>Available nodes</h2>
 Total online: <% integer_to_list(length(Data)) %>
 <ul>
   <% [index(A) || A <- Data] %>
</ul>
</body>
</html>

<%@ index(N) %>
<li><% atom_to_list(N) %></li>

Now compile it with “erltl:compile(”index.et)” and put in the same path as your mochiweb app (below).

Next setup the Mochiweb application:

-module(test_templates_web).

-export([start/1, stop/0, loop/2]).

start(Options) ->
    {DocRoot, Options1} = get_option(docroot, Options),
    Loop = fun (Req) ->
		   ?MODULE:loop(Req, DocRoot)
	   end,
    mochiweb_http:start([{name, ?MODULE}, {loop, Loop} | Options1]).

stop() ->
    mochiweb_http:stop(?MODULE).

loop(Req, DocRoot) ->
    "/" ++ Path = Req:get(path),
    case Req:get(method) of

	'GET' ->
           %% This call returns a list of nodes the Erlang application is connected to -
           %% a list like this: [node1@here.com,node2@here.com]
           NodeData = nodes(),

           %% Pass the data to the template
           Outty = index:render(NodeData),

           %% Send the output (String) back to the browser
           Req:ok({"text/html",Outty});

       _ ->
           Req:not_found()
    end.

Inside the ‘GET’ above, I pass the data to the compiled template, then send it back to the browser.

Obviously I’ve glossed over a few details, but hopefully you get the idea. It may not be as “elegant” as a Rails app, but it’s blazing fast!

Trackbacks

Unfortunately, due to spammers I've had to close both trackbacks and comments.

Comments

Leave a response

Comments