lua resty template && openresty 使用

1. 安装

  1. luarocks install lua-resty-template

2. 使用

配置模板页面位置

有多种方式:

a. 直接使用root 目录

代码如下:

  1. location /{
  2. root html;
  3. content_by_lua '
  4. local template = require "resty.template"
  5. template.render("view.html",{ message ="Hello, World!"})
  6. ';
  7. }

view.html

  1. <!DOCTYPE html>
  2. <html>
  3. <body>
  4. <h1>{{message}}</h1>
  5. </body>
  6. </html>

b. set $template_root

代码如下:

  1. http {
  2. server {
  3. set $template_root /usr/local/openresty/nginx/html/templates;
  4. location /{
  5. root html;
  6. content_by_lua '
  7. local template = require "resty.template"
  8. template.render("view.html",{ message ="Hello, World!"})
  9. ';
  10. }
  11. }
  12. }

c. set template_location(原理:ngx.location.capture from /templates)

代码如下:

  1. http {
  2. server {
  3. set $template_location /templates;
  4. location /{
  5. root html;
  6. content_by_lua '
  7. local template = require "resty.template"
  8. template.render("view.html",{ message ="Hello, World!"})
  9. ';
  10. }
  11. location /templates {
  12. internal;
  13. alias html/templates/;
  14. }
  15. }

3. 参考文档

  1. https://github.com/bungle/lua-resty-template