模板引擎 ctemplate

openkk 12年前
     <p>ctemplate (Google-ctemplate)的设计哲学是轻量级,快速,且逻辑和界面分离,因此和ClearSilver和Teng是有一些差异的。比如Ctemplate就没有模板函数,没有条件判断和循环语句(当然,它可以通过变通的方式来实现)。</p>    <p>ctemplate大体上分为两个部分,一部分是模板,另一部分是数据字典。模板定义了界面展现的形式(V),数据字典就是填充模板的数据(M),你自己写业务逻辑去控制界面展现(C),典型的MVC模型。</p>    <p>ctemplate模板中有四中标记,对应的数据字典也有不同的处理方式:</p>    <ul>     <li>变量,{{变量名}},用两个大括号包含的就是变量名,在c++代码中,可以对变量赋值,任何类型的值都可以(如字符,整数,日期等)。</li>     <li>片断,{{#片断名}},片断在数据字典中表现为一个子字典,字典是可以分级的,根字典下面有多级子字典。片断可以处理条件判断和循环。</li>     <li>包含,{{>模板名}}包含指的是一个模板可以包含其他模板,对应的也是一个字字典。</li>     <li>注释,{{!注释名}},包含注释。</li>    </ul> 一份演示了完整四种标记的例子如下    <pre class="prettyprint">Hello {{NAME}}, You have just won ${{VALUE}}! {{#IN_CA}}Well, ${{TAXED_VALUE}}, after taxes.{{/IN_CA}}</pre>处理的C++代码如下:    <pre class="brush:cpp; toolbar: true; auto-links: false;">#include  #include  #include    #include    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", "%.2f", winnings * 0.83);   // 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; }</pre>    <p><strong>项目主页:</strong><a href="http://www.open-open.com/lib/view/home/1322965320890" target="_blank">http://www.open-open.com/lib/view/home/1322965320890</a></p>