libctemplate——C语言模块引擎简介及使用

前言

  首先声明此libctemplate不是Google那个ctemplate。这个库是用C语言实现的,只有一个实现文件和一个头文件。Gooogl的ctemplate是C++实现的,和线程还扯上了关系。这两个库的具体代码还没看,从介绍及例子上看,libctemplate应该比Google的那个更轻量级,在嵌入式的web开发中可能更适合。

  因为前段时间在做嵌入式设备中的web开发,使用c语言CGI方式开发web服务器端。上网查找资料时发现“C语言也能干大事之C语言开发网站教程”,因此知道libctemplate,有了这个模板引擎,再配合cgic这个库,开发起web来会方便很多。关于这个库的介绍看官方文档可能会更准确详尽。

官网:http://libctemplate.sourceforge.net/

手册:http://libctemplate.sourceforge.net/doc.html

C语言也能干大事之C语言开发网站教程:http://www.rupeng.com/Courses/Index/34

例子

  一个简单的例子,说明这个库的简单应用。例子总共分为两部分,一部分是模板文件,也就是html文件;一部分是c语言写的CGI程序。例子比较简单,代码需要分析解析的地方请看代码注释。

html代码

 1 <html>
 2 <head>
 3     <title>user</title>
 4 </head>
 5 <body>
 6     姓名:<TMPL_VAR name="Name"/><br />
 7     年龄:<TMPL_VAR name="Age"/><br/>
 8     家族成员:
 9     <table border=1>
10     <tr><td>姓名</td><td>生日</td></tr>
11     <TMPL_LOOP name="Persons">
12         <tr><td><TMPL_VAR name="Name"/></td><td><TMPL_VAR name="Age"/></td></tr>
13     </TMPL_LOOP>
14     </table>
15 </body>
16 </html>

CGI程序

 1 #include <stdio.h>
 2 #include "cgic.h"              // cgic库的头文件
 3 #include "ctemplate.h"         // libctemplate库的头文件
 4 
 5 // main已经定义在cgic.c中,在main函数中会调用cgiMain
 6 int cgiMain(int argc, char **argv)
 7 {
 8     TMPL_varlist *mainList = 0;
 9     TMPL_varlist *personList = 0;
10     TMPL_loop    *loop = 0;
11     
12     // 使用cgic接口,输出文档类型
13     cgiHeaderContentType("text/html;charset=gbk");
14     
15     // 把两个家族成员的值加到一个TMPL_loop中,用来显示在表格中
16     // 所有的值都必须是字符串形式
17     personList = TMPL_add_var(0, "Name", "lucy", "Age", "16", 0);
18     loop = TMPL_add_varlist(loop, personList);
19     
20     personList = TMPL_add_var(0, "Name", "lily", "Age", "17", 0);
21     loop = TMPL_add_varlist(loop, personList);
22     
23     // 再把这个TMPL_loop嵌到值列表中,名字是“Persons”,要与模板中的名字一样
24     mainList = TMPL_add_loop(mainList, "Persons", loop);
25     
26     // 再往值列表中加一些值
27     mainList = TMPL_add_var(mainList,"Name","uncle wang","Age","38",0);
28     
29     // 把值列表在模块中显示,模块文件的路径根据需要更改
30     TMPL_write("web/cgi-bin/user.html",0,0,mainList,cgiOut,cgiOut);
31     
32     return 0;
33 }

布署运行

  把CGI程序加上cgic、ctemplate一起编译,把编译出来的程序和html按指定目录放置后,可以直接执行,运行结果如下。即把值列表中的值替换模板中的指定变量,生成一串html字符流。

 1 [/mnt/goahead]./user2 
 2 Content-type: text/html;charset=gbk
 3 
 4 <html>
 5 <head>
 6     <title>user</title>
 7 </head>
 8 <body>
 9     姓名:xiaomin<br />
10     年龄:38<br/>
11     家族成员:
12     <table border=1>
13     <tr><td>姓名</td><td>生日</td></tr>
14     
15         <tr><td>lucy</td><td>16</td></tr>
16     
17         <tr><td>lily</td><td>17</td></tr>
18     
19     </table>
20 </body>
21 </html>
22 [/mnt/goahead]

  把程序和模板布署到web server对应目录中,即可在浏览器中测试。上面例子的执行结果如下图所示。

 

原文地址:https://www.cnblogs.com/qinwanlin/p/5106324.html