魏长东

weichangdong

lua html模板(win)

set $template_location "/html";   
	set $template_root "D:/openresty/html/html";
	

	
	location /html_html {  
		default_type 'text/html';  
		content_by_lua_file "html/html/test_template_1.lua";   
	}  
	
	location /html_html2 {  
		default_type 'text/html';  
		content_by_lua_file "html/html/test_template_2.lua";   
	} 
	
		
	location /html_html3 {  
		default_type 'text/html';  
		charset utf-8;
		#ngx.header['Content-Type']="text/html;charset=UTF-8"
		content_by_lua_file "html/html/test_template_3.lua";   
	} 

test_template_1.lua
local template = require("resty.template")  
template.render("t1.html")

test_template_2.lua
local template = require("resty.template")  
--是否缓存解析后的模板,默认true  
template.caching(true)  
--渲染模板需要的上下文(数据)  
local context = {title = "im title"}  
--渲染模板  
template.render("t1.html", context)  
  
  
ngx.say("<br/>")  
--编译得到一个lua函数  
local func = template.compile("t1.html")  
--执行函数,得到渲染之后的内容  
local content = func(context)  
--通过ngx API输出  
ngx.say(content) 



test_template_3.lua
local template = require("resty.template")  
  
local context = {  
    title = "测试",  
    name = "张三",  
    description = "<script>alert(1);</script>",  
    age = 20,  
    hobby = {"电影", "音乐", "阅读"},  
    score = {语文 = 90, 数学 = 80, 英语 = 70},  
    score2 = {  
        {name = "语文", score = 90},  
        {name = "数学", score = 80},  
        {name = "英语", score = 70},  
    }  
}  
  
template.render("t3.html", context)  

 

 

 

都实现了。