Monday, August 27, 2012

qt-mustache Templating Library

I had a need for a templating library for use with several Qt projects.  I was looking preferably for something simple that is easy to drop into a project and has a familiar syntax.  Existing libraries that I found included Grantlee (a featureful library using Django template syntax), Qustache and QCTemplate (a thin wrapper around Google's CTemplate library for logic-free templates which inspired Mustache).  None of these were quite what I was looking for, so I wrote a small library which uses the popular Mustache template syntax.

Example Usage:
#include "mustache.h"

QVariantHash contact;
contact["name"] = "John Smith";
contact["email"] = "";

QString contactTemplate = "<b>{{name}}</b> <a href=\"mailto:{{email}}\">{{email}}</a>";

Mustache::Renderer renderer;
Mustache::QtVariantContext context(contact);

QTextStream output(stdout);
output << renderer.render(contactTemplate, &context);
 <b>John Smith</b> <a href=""></a>
The main feature, like Mustache itself, is that it doesn't have that many features.  The lack of logic constructs in templates prevents application logic from ending up in the templates themselves. Other 'features' are:

  • Lightweight.  Two source files.  The only dependency is QtCore.
  • Efficient.
  • Complete 'mustache' syntax support (values, sections, inverted sections, partials, lambdas, escaping). I may look at incorporating one or two facilities from Handlebars in future.
  • The standard data source is a QVariantMap or QVariantHash.  There is an interface if you wish to provide your own - eg. if you wanted to use a QAbstractItemModel as the data structure to fill in a template.
  • Partial templates can be specified as an in-memory map or .mustache files in a directory.  You can also provide your own loader if you want to be able to fetch partial templates from a different source.

The code is available from github (BSD license):