Mustache Templating with Webscript

Mustache is a popular templating language, often used for generating HTML. It's available in more than a dozen languages, and there are several implementations in Lua (the language used by Webscript). Because we saw a number of users generating HTML from their scripts, we decided to add support for one of the Lua implementations to our standard module library. We chose Lustache, though there's no reason you can't use a different module.

To demonstrate Lustache, we built a small example that builds on the RSS parsing example that we blogged about earlier this week.

In this example, we retrieve an RSS feed and convert it to an HTML page with a list of links:

local template =
[[
<!doctype html>
<html>
<head>
        <title>{{feed.title}}</title>
</head>
<body>
        <h1><a href="{{{feed.link}}}">{{feed.title}}</a></h1>
        <ul>
        {{#entries}}
                <li><a href="{{{link}}}">{{title}}</a></li>
        {{/entries}}
        </ul>
</body>
</html>
]]

local feedparser = require 'feedparser'
local response = http.request { url =
        request.query.feed or 'http://blog.webscript.io/rss.xml'
}
local parsed = feedparser.parse(response.content)

local lustache = require 'lustache'
return lustache:render(template, parsed),
        {['Content-Type']='text/html; charset=utf-8'}

Note that substitutions with double curly braces are automatically HTML-escaped, while those with triple curly braces are not.

This example is also available on the examples page.