Bambang pramusintha

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.

  1. Hi superb website! Does running a blog such as this require a
    large amount of work? I’ve virtually no expertise in coding but I had been hoping to start my own blog soon. Anyhow, should you have any recommendations or techniques for new blog owners please share. I understand this is off topic however I simply needed to ask. Thank you!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: