Google ctemplate-c++テンプレートエンジン

9966 ワード

1概要
Web開発を行う場合、従来のCGI方式を用いると、C/C++プログラムではロジックもページ表示内容も処理し、混乱します.テンプレートエンジンにより、論理と表示を分離できます.Google CTemplateは、オープンソースのC++テンプレートエンジンの1つです.ctemplateを使用するとhtmlだけでなくxml,jsonなどのフォーマットのコンテンツも生成できます.
ソースアドレス:https://github.com/OlafvdSpek/ctemplate
 
2例
2.1テンプレートファイル
<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>

 
2.2 C++エンドコード
#include 
#include <string>
#include 
#include 

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.html", ctemplate::DO_NOT_STRIP);
    tpl->Expand(&output, &dict);
    printf("%s
", output.c_str()); return 0; }

 
3.3出力ページの内容の実行
root@qwl-desktop:~/ctemplate-test# ./example 
<html>
<head>
<title>ctemplate    title>
head>

<body>
    example
    <table>
        
        <tr>
            <td>1td>
            <td>2td>
            <td>0td>
        tr>
        
        <tr>
            <td>1td>
            <td>2td>
            <td>1td>
        tr>
        
    table>
body>
html>