前言
首先聲明此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對應目錄中,即可在瀏覽器中測試。上面例子的執行結果如下圖所示。

