1 简介
https://github.com/bungle/lua-resty-template
如果学习过JavaEE中的servlet和JSP的话,应该知道JSP模板最终会被翻译成Servlet来执行;
而lua-resty-template模板引擎可以认为是JSP,其最终会被翻译成Lua代码,然后通过ngx.print输出
这是第三方库,需要安装
2 语法介绍
2.1 标签语法
1){* expression *}
表达式(变量)转义输出,类似于Spring MVC中输出ModelAndView中的变量;
2){{ expression }}
表达式(变量)做HTML转义输出;;
3){% lua code %}
Lua代码执行块;
4){( template )}
所包含的模板文件,类似于JSP中的include标签,一般我们可以将网页通用的head和footer包含进来;
5){[ expression ]}
包含表达式文件 (表达式结果),可以这样使用:{["file.html", { message = "Hello, World" } ]},上面是官方文档给的注释,个人觉得和{(template)}没啥区别,直接在上面写表达式会报错;
6){# comment #}
代码注释(不输出、不执行);
7){-block-}...{-block-}
该标签对的内容会被识别为一个Lua代码块,(请注意block不要用成verbatim或raw了,否则会被识别为纯文本输出);
8){-verbatim-}...{-verbatim-} 或者 {-raw-}...{-raw-}
两类标签的内容不会被lua-resty-template解析,并作为纯文本输出;
2.2 配置模板位置
使用lua-resty-template,可以通过下面两种方式来配置模板文件的位置,在server下可配置
template_root (set $template_root /var/www/site/templates)
或
template_location (set $template_location /templates)
如果在Nginx配置中没有这些设置,则使用ngx.var.document_root的值。 如果设置了template_location,并且正常返回(状态码200),则使用其渲染。如果找不到,将回溯到template_root或document_root。
3 下载安装
3.1 下载解压
https://github.com/bungle/lua-resty-template
3.2 上传
将解压后的下面templete.lua文件和templete文件夹上传到openresty/lualib/resty目录下
4 http使用示例
4.1 示例(使用reader函数直接构建模板和内容)
4.1.1 修改nginx配置文件
在server加一个location配置
location /lua-templete {
default_type text/html;
content_by_lua_file lua/lua-resty-template.lua;
}
4.1.2 添加文件lua-resty-template.lua
内容
-- Using template string
local template = require "resty.template"
template.render([[
<!DOCTYPE html>
<html>
<body>
<h1>{{message}}</h1>
</body>
</html>]], { message = "Hello, World!" })
4.1.3 重启后访问
4.2 示例(使用html模板文件)
4.2.1 nginx配置文件
在server下条件下面配置,配置模板文件位置
set $template_root /usr/local/openresty/nginx/lua/templete;
4.2.2 添加view.html文件
内容
<!DOCTYPE html>
<html>
<body>
<h1>{{message}}</h1>
</body>
</html>
4.2.3 修改lua-resty-template.lua
写法1
local template = require "resty.template"
-- Using template.new
local view = template.new "view.html"
view.message = "Hello, World!"
view:render()
写法2
local template = require "resty.template"
-- Using template.new
template.render("view.html", { message = "Hello, World!" })
4.2.4 重启后访问
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)