Illusory Follies Andrew Flanagan's Blog

30Mar/090

Google CTemplate

I just realized that I reinvented the wheel a month or so... I had a need for a nice templating language and although I did look for a solution that already existed, I didn't look hard enough. Google CTemplate is exactly what I wanted. My solution was basically to create this from scratch while ignoring all the complexities that I thought I wouldn't need. The result works (and may even be faster) but it feels clunky and it's not very flexible. You learn something new every day. Maybe with Rev2 of our release I'll start using this -- it certainly would be easier and the API is already documented.

From their website:

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 we assume is stored in the file 'example.tpl':

#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 = 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");
  }
  google::Template* tpl = google::Template::GetTemplate("example.tpl",
                                                        google::DO_NOT_STRIP);
  std::string output;
  tpl->Expand(&output, &dict);
  std::cout << output;
  return 0;
}
Filed under: Geekiness Leave a comment
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

No trackbacks yet.