Ctemplate System

Status: Current   (as of 25 April 2008)

Welcome to the C++ CTemplate system! (This project was originally called Google Templates, due to its origin as the template system used for Google search result pages, but now has a more general name matching its community-owned nature.)

As a quick start, here's a small but complete program that uses this template library. For more details see, the links below.

Template file example.tpl

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

C++ program example.cc

   #include <stdlib.h>
   #include <string>
   #include <iostream>
   #include <ctemplate/template.h>
   int main(int argc, char** argv) {
      ctemplate::TemplateDictionary dict("example");
      dict.SetValue("NAME", "John Smith");
      int winnings = rand() % 100000;
      dict.SetIntValue("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) {
        dict.ShowSection("IN_CA");
      }
      std::string output;
      ctemplate::ExpandTemplate("example.tpl", ctemplate::DO_NOT_STRIP, &dict, &output);
      std::cout << output;
      return 0;
   }

Compiling and linking (using gcc)

   gcc -o example example.cc -lctemplate_nothreads

I can use the "nothreads" library because example.cc doesn't use threads. If example.cc were threaded, I would do something like this instead:

   gcc -o example example.cc -lctemplate -pthread

See the README for more details about the two different ctemplate libraries.

In-depth Documentation

  1. Howto: Introduction to the Ctemplate system, and a tutorial for using it.
  2. Auto Escape: Guide to using the optional Auto Escape mode to protect your web application better against XSS.
  3. Tips: Advice, tips, and recommendations for best practices with templates, to make them easier to write and maintain, and to avoid common template mistakes.
  4. Examples: Some example templates and application code that uses them. These are taken from actual Google applications.

Craig Silverstein
Last modified: Mon Feb 22 10:59:03 PST 2010