zoukankan      html  css  js  c++  java
  • 5、ctemplate简介

    1、linux下的web开发,动态页面生成很费周折,通常利用cgi接受请求,然后返回页面给请求端。代码逻辑和显示逻辑写在一起,是一件很痛苦的事情C++google ctemplate便是解决这个问题。【1

    ctemplate解决的主要问题是将文字表达和逻辑分离开来:文字模板解决如何用合适的文字和形式来表示问题,而逻辑问题则由文字模板的调用者在源代码中完成。

    ctemplate大体上分为两个部分,一部分是模板,另一部分是数据字典。模板定义了界面展现的形式(V),数据字典就是填充模板的数据(M),你自己写业务逻辑去控制界面展现(C),典型的MVC模型。

    2、ctemplate模板中有四中标记,对应的数据字典也有不同的处理方式:

    变量,{{变量名}},用两个大括号包含的就是变量名,在c++代码中,可以对变量赋值,任何类型的值都可以(如字符,整数,日期等)。

    片断,{{#片断名}},片断在数据字典中表现为一个子字典,字典是可以分级的,根字典下面有多级子字典。片断可以处理条件判断和循环

    包含,{{>模板名}}包含指的是一个模板可以包含其他模板,对应的也是一个字字典。

    注释,{{!注释名}},包含注释。

    3、示例程序

    模板

    example.tpl
    Hello{{NAME}},
    You have just won ${{VALUE}}!
    {{#IN_CA}}
    Well, ${{TAXED_VALUE}}, after taxes.
    {{/IN_CA}}

    字典逻辑

    .cpp
    #include<stdlib.h>
    #include
    <string>
    #include
    <iostream>
    #include
    <ctemplate/template.h>

    int main(int argc,char** argv)
    {
    ctemplate::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");
    }
    std::
    string output;
    ctemplate::ExpandTemplate(
    "example.tpl", ctemplate::DO_NOT_STRIP, &dict, &output);
    std::cout
    << output;
    return 0;
    }

    运行结果

    View Code
    HelloJohn Smith,
    You have just won $
    89383!

    Well, $
    74187.89, after taxes.

    4、说明,编译时:

    g++ -g -o test_ct test_template.cpp -lctemplate

    要加ctemplate静态库来包含所引用的文件。

    参考

    1http://www.blogjava.net/xiaomage234/archive/2007/12/24/170174.html

    2http://baike.baidu.com/view/5835966.htm

    3http://zsulwj.blog.163.com/blog/static/35326925200811934454946/

    4ctemplate安装包下载地址:

    http://code.google.com/p/google-ctemplate/downloads/list

    5】示例程序

    http://code.google.com/p/google-ctemplate/

  • 相关阅读:
    ubuntu配置bonding 武汉
    桌面图标加载与存储
    launcher 图标删除分析
    Inflater
    Android屏幕元素层次结构
    简述Android触摸屏手势识别
    RelativeLayout && inflate
    manifest分析
    vacantcell缓存分析
    桌面快捷键和桌面livefolder
  • 原文地址:https://www.cnblogs.com/mydomain/p/2169029.html
Copyright © 2011-2022 走看看