Chinaunix首页 | 论坛 | 博客
  • 博客访问: 8075214
  • 博文数量: 594
  • 博客积分: 13065
  • 博客等级: 上将
  • 技术积分: 10324
  • 用 户 组: 普通用户
  • 注册时间: 2008-03-26 16:44
个人简介

推荐: blog.csdn.net/aquester https://github.com/eyjian https://www.cnblogs.com/aquester http://blog.chinaunix.net/uid/20682147.html

文章分类

全部博文(594)

分类: C/C++

2012-08-15 22:51:35

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\n", output.c_str());
    
    return 0;
}

编译:
g++ -g -o x x.cpp ./lib/libctemplate_nothreads.a -I./include
执行x输出内容如下:
ctemplate示例模板

    example
   
        
       
           
           
           
       
        
       
           
           
           
       
        
   
120
121

阅读(6747) | 评论(1) | 转发(0) |
给主人留下些什么吧!~~

xiaoyao38572013-01-10 13:41:40

C++对HTML模板的处理!以前竟没想过!