OpenResty 中模板渲染引擎 lua-resty-template

OpenResty Lua LuaRocks About 1,846 words

项目介绍

lua-resty-templateLuaOpenResty中的模板渲染引擎。由Kong网关核心工程师bungle开源,京东商城使用此项目完成相关开发。

开源地址:https://github.com/bungle/lua-resty-template

快速入门

安装

luarocks install lua-resty-template

content_by_lua_file

local template = require "resty.template"
template.render("post.html", { message = "Hello, Post!" })

post.html

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

输出

<!DOCTYPE html>
<html>
<body>
  <h1>Hello, World!</h1>
</body>
</html>

模板语法

  • {{expression}}:输出传递的值,转义html相关标签
  • {*expression*}:输出传递的值
  • {% lua code %}:使用lua代码
  • {(template)}:引入html共用页面
  • {(base.html, { title = "Hello, World" } )}:引入html共用页面,并传递相关值
  • {-verbatim-}...{-verbatim-}/{-raw-}...{-raw-}:可原样输出模板语法
  • {# comments #}:在模板中使用注释,不会被执行和输出

更多详细语法请查阅官方文档:https://github.com/bungle/lua-resty-template

简要示例

{{expression}}

message = "<h1>Hello World</h1>"

输出:<h1>Hello World</h1>

<body>
{{message}}
</body

{*expression*}

message = "<h1>Hello World</h1>"

输出:Hello World(带h1样式)

<body>
{*message*}
</body

{% lua code %}

使用if判断。

{% if 1 == 2 then %}
    <h1>1 = 2</h1>
{% else %}
    <h1>1 ~= 2</h1>
{% end %}

{(template)}

引入共用模板,传递titlekeywordsdescription等属性。

{(base.html, { title = ngx.ctx.post.title, keywords = ngx.ctx.post.keywords, description = ngx.ctx.post.description } )}

base.html

<title>{{title}} | 程序员技术之旅</title>
<meta name="keywords" content="{{keywords}}"/>
<meta name="description" content="{{description}}"/>

{-raw-}...{-raw-}

可原样输出lua-resty-template中的语法。

输出:{{message}}

<body>
{-raw-}{{message}}{-raw-}
</body>

{# comments #}

模板中注释,帮助开发者记录,不会被执行和输出。

<body>
内容123
{# This is comment #}
内容456
</body>

开源案例

https://github.com/fendoudebb/z-blog-openresty

Views: 6,293 · Posted: 2020-02-28

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh