ctemplate使用

 

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 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;
}

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

News

ctemplate 0.91 introduces the beginning of some API changes, as I look to clean up the API in preparation for ctemplate 1.0. After 1.0, the API will remain backwards compatible, but until that time, the API may change. Please take a look at the ChangeLog to see if any of these changes affect you.

One change is the introduction of a new PerExpandData class, which holds some state that was formerly in the TemplateDictionary class. I'm still not sure if this class is a good idea, if it should be separate from TemplateDictionary or a member, or what functionality should move there (for instance, should SetTemplateGlobal move there, since template-global variables are really, in some sense, per-expand variables?) If you have any feedback, ideally based on your own experience using the current API, feel free to post it at google-ctemplate@googlegroups.com.

ctemplate also has several new features, including the addition of "separator" sections, and the ability to change the markup character (from {{). See the ChangeLog for a complete list, and the howto documentation for more details on these new features.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值