Google开源html模板库ctemplate的完整使用示例


ctemplate是Google开源的一个C++版本html模板替换库。有了它,在C++代码中操作html模板是一件非常简单和高效的事。通过本文,即可掌握对它的简单使用。

示例html模板文件example.htm内容如下:

ctemplate示例模板

{{table1_name}}

{{#TABLE1}}

{{/TABLE1}}

{{field1}} {{field2}} {{field3}}

模板中的变量使用{{}}括起来,

而{{#TABLE1}}和{{/TABLE1}}表示一个循环。

C++代码x.cpp文件内容如下:

#include 
#include 
#include 
int main()
{
  ctemplate::TemplateDictionary dict("example");
  dict.SetValue("table1_name", "example");
  // 为节省篇幅,这里只循环一次
  for (int i=0; i<2; ++i)
  {
    ctemplate::TemplateDictionary* table1_dict;
    table1_dict = dict.AddSectionDictionary("TABLE1");
    table1_dict->SetValue("field1", "1");
    table1_dict->SetValue("field2", "2");
    // 这里有点类似于printf
    table1_dict->SetFormattedValue("field3", "%d", i);
  }
  std::string output;
  ctemplate::Template* tpl;
  tpl = ctemplate::Template::GetTemplate("example.htm", ctemplate::DO_NOT_STRIP);
  tpl->Expand(&output, &dict);
  printf("%s
", output.c_str());
  return 0;
}

编译:

g++ -g -o x x.cpp ./lib/libctemplate_nothreads.a -I./include

执行x输出内容如下:

ctemplate示例模板

example

120

121

优质内容筛选与推荐>>
1、fenye
2、J2EE学习篇之--JQuery技术详解 分类: JavaWeb 2014-06-18 11:35 1958人阅读 评论(1) 收藏
3、xcode7.1新建项目等问题
4、Cytoscape画图初探
5、django模板系统(下)


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号