zoukankan      html  css  js  c++  java
  • google ctemplate——c++模板引擎

     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
    ", 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>
  • 相关阅读:
    V2EX 上收藏Top200
    在heroku上部署gost代理服务端
    nano编辑器使用教程
    Amazon EC2免费VPS防止超额被扣钱三大方法:流量 硬盘读写 运行时长
    Go语言开发环境配置
    HTML5 and CSS3 开发
    使用 Eclipse PhoneGap 构建 Android 应用程序入门
    脚本之家
    CSS网页布局全精通
    使用面向 iOS 的本机插件扩展 PhoneGap
  • 原文地址:https://www.cnblogs.com/qinwanlin/p/5113228.html
Copyright © 2011-2022 走看看