Openresty中使用lua-resty-template

881 阅读2分钟

介绍

Lua中有很多模版引擎,如lua-resty-template可以渲染页面,类似于java web开发中使用的jsp最终会被翻译为Servlet来执行,lua-resty-template模版最终被翻译为Lua代码,然后通过nginx.print输出。

下载和使用

github.com/bungle/lua-… 下载后将lib/resty下面的template.lua放到我们安装的openresty下面的lualib/resty下。然后我们就可以通过如下方式引用:

local template = require("resty.template")

模版标签语法

  • {{expression}}, 写入表达式的结果 - html 转义
  • {*expression*}, 写入表达式的结果
  • {% lua code %}, 执行 Lua 代码
  • {(template)}, 所包含template文件,类似于jsp中的include标签
  • {[expression]}, 包含expression文件(表达式的结果),可这样使用{["file.html", { message = "Hello, World" } ]},和{(template)}差不多
  • {-verbatim-}...{-verbatim-}{-raw-}...{-raw-}是标签内部不被lua-resty-template解析,纯文本输出
  • {-block-}...{-block-} 标签内被识别为lua代码块

模版位置

对于配置我们需要注意下面两个配置指令:

  • template_root (set $template_root /var/www/site/templates)
  • template_location (set $template_location /templates)

如果上面的配置没有在nginx配置中,则使用ngx.var.document_root。如果template_location设置并且返回状态码200则使用该配置渲染。如果返回状态码200以外的任何内容,则使用template_root或者document_root。

建议首先template_root,如果实在有问题再使用template_location,尽量不要通过root指令定义的document_root加载,因为其本身的含义不是给本模板引擎使用的。

lua-resty-template 2.0可以覆盖$template_root 和 $template_location 通过如下lua代码:

local template = require "resty.template".new({
  root     = "/templates",
  location = "/templates" 
})

简单使用

使用 template.new 和template.render两种方式渲染:

local template = require "resty.template"
-- 1. template.new
--local view = template.new "view.html"
--view.message = "Hello, World!"
--view:render()

-- 2. template.render
-- template.render("view.html", { message = "Hello, World!" })

-- 3.template.compile
--编译得到一个lua函数
local func = template.compile("view.html")
local world    = func{ message = "Hello, World!" }
--执行函数,得到渲染之后的内容
local content = func(context)
ngx.say(content, world)

其中view.html

<!DOCTYPE html>
<html>
<body>
  <h1>{{message}}</h1>
</body>
</html>

另外我们简单配置下nginx.conf

nginx.conf

worker_processes 1;
error_log  logs/error.log;

events {
  worker_connections 1024;
}

http {
  lua_package_path "$prefix/lua/?.lua;$prefix/libs/?.lua;;";
  server {
    server_name localhost;
    listen 8080;
    charset utf-8;
    set $LESSON_ROOT lua/;
    error_log  logs/error.log;
    access_log logs/access.log;
    location /test {
      set $template_root /Users/wukong/Desktop/tool/openresty-test/template/html/html;
      set $template_location /Users/wukong/Desktop/tool/openresty-test/template/html;
      default_type text/html;
      content_by_lua_file $LESSON_ROOT/test.lua;
    }

  }

}

我们请求来看下:

image.png

www.iteye.com/blog/jinnia…

github.com/bungle/lua-…