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>
  • 相关阅读:
    [Leetcode 11] 112 Path Sum
    [Leetcode 14] 7 Reverse Integer
    [Leetcode 12] 126 Word Ladder II TO_BE_ADDED
    [Leetcode 13] 1 Two Sum
    [Leetcode 7] 101 Symmetric Tree
    [Leetcode 9] 110 Balanced Binary Tree
    [Leetcode 15] 8 String to Integer (atoi)
    [Leetcode 8] 104 Maximum Depth of Binary Tree
    [Leetcode 16] 9 Palindrome Number
    [Leetcode 10] 111 Minimum Depth of Binary Tree
  • 原文地址:https://www.cnblogs.com/qinwanlin/p/5113228.html
Copyright © 2011-2022 走看看