简介:google ctemplate:简单易用的文字模板

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

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值