簡介:google ctemplate:簡單易用的文字模板
CTemplate 是一個簡單實用、功能強大的文字模板(template language),適用于使用C++語言開發的應用程序。其解決的主要問題是將文字表達和邏輯分離開來:文字模板解決如何用合適的文字和形式來表達的問題,而邏輯問題則由文字模板的調用者在源代碼中完成。
下面有一個簡單的例子讓我們初步了解其概念,介紹了如何在你的程序中應用CTemplate:
首先創建一個模板文件,命名為example.tpl,以文本方式輸入以下內容:
{{ NAME }}你好 ,
恭喜你中獎了,獎金總額是:$ {{ VALUE }}!
{{ #IN_CA}}您應繳納的稅金總額為: ${{TAXED_VALUE}}。 {{/IN_CA}}
在C++程序中我們可以這樣調用:
#include <stdlib.h>
#include <string>
#include <iostream>
#include <google/template.h>
int main ( int argc , char ** argv ) {
google :: TemplateDictionary dict ( "example" );
dict . SetValue ( "NAME" , "John Smith" );
int winnings = rand () % 100000 ;
dict . SetIntValue ( "VALUE" , winnings );
dict . SetFormattedValue ( "TAXED_VALUE" , "%
// For now, assume everyone lives in CA.
// (Try running the program with a 0 here instead!)
if ( 1 ) {
dict . ShowSection ( "IN_CA" );
}
google :: Template * tpl = google :: Template :: GetTemplate ( "example.tpl" ,
google :: DO_NOT_STRIP );
std :: string output ;
tpl -> Expand (& output , & dict );
std :: cout << output ;
return 0 ;
}
如果你感興趣的話可以參考完整的幫助文檔:
posted on 2010-03-04 12:15 肥仔 閱讀(838) 評論(0) 編輯 收藏 引用 所屬分類: 模板引擎