尝试使用google-template模板引擎

来源:互联网 发布:怎样使淘宝排名靠前 编辑:程序博客网 时间:2024/05/20 07:14

本文由导学宝转自: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>
 
intmain(intargc, char** argv) {
    ctemplate::TemplateDictionary dict("example");
    ctemplate::TemplateDictionary* section = NULL;
    std::string output;
 
    intwinnings = 0;
    doubleratio = 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(inti = 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;
 
    return0;
}

结果

?
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