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"] = "john.smith@gmail.com";

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);
Outputs:
 <b>John Smith</b> <a href="mailto:john.smith@gmail.com">john.smith@gmail.com</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): https://github.com/robertknight/qt-mustache

3 comments:

Anonymous said...

How is it different from Qustache?

I'm interested in using mustache from Qt.
What is the difference between both?

Unknown said...

Qustache and qt-mustache both solve the same problem. The differences that I know of are:

- Qustache is GPLv3 licensed. qt-mustache is BSD-licensed.

- qt-mustache is a little simpler to deploy (one source file, one header file, only dependency is QtCore)

- I would expect qt-mustache to be faster, since it is implemented with basic string operations and a simple parser. Qustache uses QRegExp.

- Qustache implements processing of Javascript in lambda tags. qt-mustache does not implement this currently.

magdalawadley said...

Lucky Casino Hotel & Racetrack - Mapyro
Lucky Casino Hotel & Racetrack 아산 출장마사지 in Gary, Gary, Gary - See 제천 출장마사지 18 traveler 포항 출장샵 reviews, 5 photos and blog posts. Rating: 구리 출장샵 2.5 오산 출장마사지 · ‎18 reviews