简介:google ctemplate:简单易用的文字模板(转载)

转自:http://blog.csdn.net/aladdina/article/details/4531736

CTemplate 是一个简单实用、功能强大的文字模板(template language),适用于使用C++语言开发的应用程序。

其解决的主要问题是将文字表达和逻辑分离开来

     文字模板解决如何用合适的文字和形式来表达的问题,而逻辑问题则由文字模板的调用者在源代码中完成。

 

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

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

 

  {{ NAME }}你好 , 
恭喜你中奖了,奖金总额是:$ {{ VALUE }}! 
{{ #IN_CA}}您应缴纳的税金总额为: ${{TAXED_VALUE}}。 {{/IN_CA}}

 

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

 1 #include <stdlib.h> 
 2 #include <string> 
 3 #include <iostream>   
 4 #include <google/template.h>   
 5 int main ( int argc , char ** argv ) { 
 6   google :: TemplateDictionary dict ( "example" ); 
 7   dict . SetValue ( "NAME" , "John Smith" ); 
 8   int winnings = rand () % 100000 ; 
 9   dict . SetIntValue ( "VALUE" , winnings ); 
10   dict . SetFormattedValue ( "TAXED_VALUE" , "%.2f" , winnings * 0.83 ); 
11   // For now, assume everyone lives in CA. 
12   // (Try running the program with a 0 here instead!) 
13   if ( 1 ) { 
14     dict . ShowSection ( "IN_CA" ); 
15   } 
16   google :: Template * tpl = google :: Template :: GetTemplate ( "example.tpl" , 
17                                                         google :: DO_NOT_STRIP ); 
18   std :: string output ; 
19   tpl -> Expand (& output , & dict ); 
20   std :: cout << output ; 
21   return 0 ; 
22 }

 

posted @ 2016-01-05 10:24  凤舞十天  阅读(323)  评论(0编辑  收藏  举报