Bambang pramusintha

Archive for the ‘ctemplate’ Category

Knowing ctemplate

In C++, ctemplate, Tutorial on September 16, 2012 at 12:35 pm

CTemplate is a simple but powerful template language for C++. It emphasizes separating logic from presentation: it is impossible to embed application logic in this template language.

Here’s an example of how to use it: not complete, but gives a good feel for what the ctemplate API looks like.

Here is a simple template file:

Hello {{NAME}},
You have just won ${{VALUE}}!
{{#IN_CA}}Well, ${{TAXED_VALUE}}, after taxes.{{/IN_CA}}

Here is a C++ program to fill in the template, which i assume is stored in the file ‘example.tpl’:

#include <cstdlib>
#include <iostream>  
#include <string>
#include <ctemplate/template.h>  

int main() {
  ctemplate::TemplateDictionary dict("example");
  int winnings = rand() % 100000;
  dict["NAME"] = "John Smith";
  dict["VALUE"] = winnings;
  dict.SetFormattedValue("TAXED_VALUE", "%.2f", winnings * 0.83);
  // For now, assume everyone lives in CA.
  // (Try running the program with a 0 here instead!)
  if (1) {
  std::string output;
  ctemplate::ExpandTemplate("example.tpl", ctemplate::DO_NOT_STRIP, &dict, &output);
  std::cout << output;
  return 0;

If you are interested in this templating language but are programming in Java, consider Hapax, which is similar to ctemplate.

%d bloggers like this: