Google開源html模板庫ctemplate的使用

openkk 12年前發布 | 33K 次閱讀 模板 模板引擎
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>
 本文由用戶 openkk 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!