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

简介:

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

 
示例html模板文件example.htm内容如下:
 
<html>
<head>
<title>ctemplate示例模板</title>
</head>
 
<body>
    `table1_name`
    <table>
        {{#TABLE1}}
        <tr>
            <td>`field1`</td>
            <td>`field2`</td>
            <td>`field3`</td>
        </tr>
        {{/TABLE1}}
    </table>
</body>
</html>
 
模板中的变量使用{{}}括起来,
而{{#TABLE1}}和{{/TABLE1}}表示一个循环。
 
C++代码x.cpp文件内容如下:
#include <ctemplate/template.h>
#include <stdio.h>
#include <string>
 
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输出内容如下:
<html>
<head>
<title>ctemplate示例模板</title>
</head>
 
<body>
    example
    <table>
        
        <tr>
            <td>1</td>
            <td>2</td>
            <td>0</td>
        </tr>
        
        <tr>
            <td>1</td>
            <td>2</td>
            <td>1</td>
        </tr>
        
    </table>
</body>
</html>




    本文转自eyjian 51CTO博客,原文链接:http://blog.51cto.com/mooon/964448 ,如需转载请自行联系原作者


相关文章
|
30天前
|
Java
有关Java发送邮件信息(支持附件、html文件模板发送)
有关Java发送邮件信息(支持附件、html文件模板发送)
30 1
|
1月前
|
XML 前端开发 数据格式
请描述如何使用`BeautifulSoup`或其他类似的库来解析 HTML 或 XML 数据。
【2月更文挑战第22天】【2月更文挑战第67篇】请描述如何使用`BeautifulSoup`或其他类似的库来解析 HTML 或 XML 数据。
|
1月前
分享82个Html经典模板,总有一款适合您
分享82个Html经典模板,总有一款适合您
22 0
|
1月前
|
前端开发 安全
分享81个Html经典模板,总有一款适合您
分享81个Html经典模板,总有一款适合您
19 2
|
9天前
|
前端开发
HTML代码示例
HTML代码示例
12 1
|
1月前
|
缓存 Java Maven
Google guava工具类库的介绍和使用
Google guava工具类库的介绍和使用
|
1月前
|
数据采集 存储 JavaScript
PHP爬虫技术:利用simple_html_dom库分析汽车之家电动车参数
本文旨在介绍如何利用PHP中的simple_html_dom库结合爬虫代理IP技术来高效采集和分析汽车之家网站的电动车参数。通过实际示例和详细说明,读者将了解如何实现数据分析和爬虫技术的结合应用,从而更好地理解和应用相关技术。
PHP爬虫技术:利用simple_html_dom库分析汽车之家电动车参数
|
1月前
分享84个Html经典模板,总有一款适合您
分享84个Html经典模板,总有一款适合您
16 0
|
1月前
|
iOS开发
分享83个Html经典模板,总有一款适合您
分享83个Html经典模板,总有一款适合您
44 7
|
1月前
分享80个Html经典模板,总有一款适合您
分享80个Html经典模板,总有一款适合您
15 0