Google Template System

Status: Current   (as of 25 April 2008)

Welcome to the Google C++ template system! 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 <google/template.h>
   int main(int argc, char** argv) {
      google::TemplateDictionary dict("example");
      dict.SetValue("NAME", "John Smith");
      int winnings = random() % 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");
      }

      google::Template* tpl = google::Template::GetTemplate("example.tpl",
                                                            google::DO_NOT_STRIP);
      std::string output;
      tpl->Expand(&output, &dict);
      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 Google Template 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: Wed Feb 15 23:21:42 PST 2006