OpenResty的lua-resty-template使用

OpenResty和TOMCAT服务器类似的提供了模板渲染的功能,类似于JAVA Web开发中的JSP。lua-resty-template插件模块并不是OpenResty官方的,官方目前提供了一个lemplate的插件,截止目前(2017-08-01)还不能作为生产环境使用。

lua-resty-template下载

下载地址:https://github.com/bungle/lua-resty-template。解压后可以看到lib/resty下面有一个template.lua,这个就是我们所需要的。可以看到在template目录中还有两个lua文件,这里我们后面再介绍。

标签语法

  • {* expression *}:表达式(变量)转义输出,类似于Spring MVC中输出ModelAndView中的变量;
  • {{ expression }}:表达式(变量)做HTML转义输出;;
  • {% lua code %}:Lua代码执行块;
  • {( template )}:所包含的模板文件,类似于JSP中的include标签,一般我们可以将网页通用的head和footer包含进来;
  • {[ expression ]}:包含表达式文件 (表达式结果),可以这样使用:{["file.html", { message = "Hello, World" } ]},上面是官方文档给的注释,个人觉得和{(template)}没啥区别,直接在上面写表达式会报错;
  • {# comment #}:代码注释(不输出、不执行);
  • {-block-}...{-block-}:该标签对的内容会被识别为一个Lua代码块,(请注意block不要用成verbatim或raw了,否则会被识别为纯文本输出);
  • {-verbatim-}...{-verbatim-} 或者 {-raw-}...{-raw-}:两类标签的内容不会被lua-resty-template解析,并作为纯文本输出;

配置模板位置

使用lua-resty-template需要注意下面两个变量

  • 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。

API使用

  • 方式一:
local template = require "resty.template"
-- Using template.new
local view = template.new "view.html"
view.message = "Hello, World!"
view:render()
  • 方式二:
local template = require "resty.template"
-- Using template.render
template.render("view.html", { message = "Hello, World!" })
  • 方式三:
local template = require "resty.template"
local func = template.compile("view.html")  
--执行函数,得到渲染之后的内容  
local content = func(context)   
ngx.say(content)

nginx配置

对于nginx.conf里面的可以使用简单配置如下:

http {
  server {
    location /test {
      default_type text/html;
      content_by_lua_file 'article/index.lua';
    }
  }
}

完整实例请参见:https://github.com/Fouy/moguhu-release

文档参考:https://github.com/bungle/lua-resty-template  http://jinnianshilongnian.iteye.com/blog/2187775