您的位置:首页 > 其它

Ctemplate的简介

2015-07-17 12:23 162 查看
CTemplate 是一个简单实用、功能强大的文字模板(template language),适用于使用C++语言开发的应用程序。 其解决的主要问题是将文字表达和逻辑分离开来:文字模板解决如何用合适的文字和形式来表达的问题,而逻辑问题则由文字模板的调用者在源代码中完成。

下面有一个简单的例子让我们初步了解其概念,介绍了如何在你的程序中应用CTemplate:

首先创建一个模板文件,命名为example.tpl,以文本方式输入以下内容:

{{ NAME }}你好 ,

恭喜你中奖了,奖金总额是:$ {{ VALUE }}!

{{ #IN_CA}}您应缴纳的税金总额为: ${{TAXED_VALUE}}。 {{/IN_CA}}

在C++程序中我们可以这样调用:

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

}

如果你感兴趣的话可以参考完整的帮助文档:How To Use the Google Template
System

再补充一个例子:

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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: