1 概述
在進行web開發時,使用傳統的CGI方式,在C/C++程序里面既要處理邏輯,也要處理頁面顯示內容,會比較混亂。可以通過模板引擎,使得邏輯與顯示的分離。Google CTemplate就是其中一個開源的C++模板引擎。使用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 <stdio.h> #include <string> #include <dlfcn.h> #include <ctemplate/template.h> 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\n", output.c_str()); return 0; }
3.3 運行輸出頁面內容
root@qwl-desktop:~/ctemplate-test# ./example <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>