尝试使用google-template模板引擎

本文由导学宝转自:http://146.185.21.137/wordpress/?p=166

很久之前用过ctemplate,但是在不久之后发现了pyton的mako模板引擎,于是就把ctemplate放在一边……最近有需要用纯c/c++来完成一个模板,于是又拿起ctemplate:)网上一堆翻译官方的教程,而没有提到如何使用loop来重复输出一段信息(比如html的列表项、日志记录等)。于是自己尝试着看看头文件,试出了一种方法。

模板

?
1
2
3
4
5
6
7
Hello {{NAME}},
You have just won ${{VALUE}}!
{{#IN_CA}}Well, ${{TAXED_VALUE}}, after taxes.{{/IN_CA}}
 
Tax histroy:
{{#LOOP}} {{TYPE}} {{VALUE}} {{TAXED_VALUE}}
{{/LOOP}}

程序

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <stdlib.h>
#include <string>
#include <iostream>
#include <ctemplate/template.h>
 
int main( int argc, char ** argv) {
     ctemplate::TemplateDictionary dict( "example" );
     ctemplate::TemplateDictionary* section = NULL;
     std::string output;
 
     int winnings = 0;
     double ratio = 0.83;
 
     //Set value
     winnings = rand () % 100000;
     dict.SetValue( "NAME" , "John Smith" );
     dict.SetIntValue( "VALUE" , winnings);
     dict.SetFormattedValue( "TAXED_VALUE" , "%.2f" , winnings * ratio);
 
     dict.ShowSection( "IN_CA" );
 
     //Print section
     for ( int i = 0;i < 10;i++) {
         winnings = rand () % 100000;
 
         section = dict.AddSectionDictionary( "LOOP" );
         section->SetValue( "TYPE" , "Income" );
 
         section->SetFormattedValue( "VALUE" ,
                 "%10.2f" ,
                 ( double )winnings);
         section->SetFormattedValue( "TAXED_VALUE" ,
                 "%10.2f" ,
                 winnings * ratio);
 
         section->ShowSection( "LOOP" );
     }
 
     //Print result
     ctemplate::ExpandTemplate( "example.tpl" ,
             ctemplate::DO_NOT_STRIP,
             &dict, &output);
     std::cout << output;
 
     return 0;
}

结果

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Hello John Smith,
You have just won $41!
Well, $34.03, after taxes.
 
Tax histroy:
  Income   18467.00   15327.61
  Income    6334.00    5257.22
  Income   26500.00   21995.00
  Income   19169.00   15910.27
  Income   15724.00   13050.92
  Income   11478.00    9526.74
  Income   29358.00   24367.14
  Income   26962.00   22378.46
  Income   24464.00   20305.12
  Income    5705.00    4735.15

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值