当前位置:网站首页>openresty lua-resty-template页面静态化
openresty lua-resty-template页面静态化
2022-08-04 21:23:00 【o_瓜田李下_o】
openresty lua-resty-template页面静态化
官网:https://github.com/bungle/lua-resty-template
template 安装
lua-resty-template安装
# 查找模块
[[email protected] bin]#opm search lua-resty-template
bungle/lua-resty-template Templating Engine (HTML) for Lua and OpenResty
bungle/lua-resty-validation Validation Library (Input Validation and Filtering) for Lua and OpenResty
bungle/lua-resty-session Session Library for OpenResty - Flexible and Secure
bungle/lua-resty-nettle Nettle (a low-level cryptographic library) Bindings for LuaJIT FFI
d80x86/lua-resty-tofu (alpha) a modern api/web framework
DevonStrawn/lua-resty-route URL Routing Library for OpenResty Supporting Pluggable Matching Engines
hamishforbes/lua-resty-qless-web Port of Moz's qless web interface to the Openresty environment.
# 安装模块
[[email protected] bin]# opm install bungle/lua-resty-template
* Fetching bungle/lua-resty-template
Downloading https://opm.openresty.org/api/pkg/tarball/bungle/lua-resty-template-2.0.opm.tar.gz
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 40890 100 40890 0 0 92474 0 --:--:-- --:--:-- --:--:-- 92302
Package bungle/lua-resty-template 2.0 installed successfully under /usr/local/openresty/site/ .
# 查看安装的模块
[[email protected] bin]# opm list
bungle/lua-resty-template 2.0
template 语法
输出内容
{
{expression}} # 输出属性
{*expression*} # 输出属性、导入文件
# 示例
local template = require "resty.template"
template.render("view.html", {
message = "Hello, World!",
})
## view.html
<h1>{
{message}}</h1> -- 输出message内容
导入模版文件
{(template)}
{[expression]}
# 示例
{(header.html)}
{(file.html, { message = "Hello, World" } )}
{[file.html]}
{["file.html", { message = "Hello, World" } ]}
{(view.html)}
{(users/list.html)} -- list.html在users目录下
执行lua代码
{% lua code %}
# 示例
{(header.html)}
<h1>{
{message}}</h1>
<ul>
{% for _, name in ipairs(names) do %} -- lua代码
<li>{
{name}}</li>
{% end %} -- lua代码
</ul>
{(footer.html)}
定义语句块,可将语句块导入其他文件
{-block-}...{-block-}
# 示例
local view = template.new("view.html", "layout.html")
view.title = "Testing lua-resty-template blocks"
view.message = "Hello, World!"
view.keywords = { "test", "lua", "template", "blocks" }
view:render()
## view.html
<h1>{
{message}}</h1>
{-aside-} -- 定义语句块
<ul>
{% for _, keyword in ipairs(keywords) do %}
<li>{
{keyword}}</li>
{% end %}
</ul>
{-aside-}
## layout.html
<!DOCTYPE html>
<html>
<head>
<title>{*title*}</title>
</head>
<body>
<article>
{*view*} -- 导入模板文件
</article>
{% if blocks.aside then %}
<aside>
{*blocks.aside*} -- 导入语句块
</aside>
{% end %}
</body>
</html>
==> 输出内容
<!DOCTYPE html>
<html>
<head>
<title>Testing lua-resty-template blocks</title>
</head>
<body>
<article>
<h1>Hello, World!</h1>
</article>
<aside>
<ul>
<li>test</li>
<li>lua</li>
<li>template</li>
<li>blocks</li>
</ul>
</aside>
</body>
</html>
注释
{# comments #}
# 示例
{# {*["foo:bar"]*} won't work, you need to use: #} -- 注释
{*context["foo:bar"]*} --输出context中key为["foo:bar"]的内容
转义字符
# 不输出message内容
<h1>\{
{message}}</h1>
==> <h1>{
{message}}</h1>,不会输出message的值
# 输出转义字符
<h1>\\{
{message}}</h1>
==> <h1>\message_value </h1>
context 上下文
# 两者等价
<h1>{
{message}}</h1> == <h1>{
{context.message}}</h1>
# 特殊格式处理
local ctx = {["foo:bar"] = "foobar"}
{# {*["foo:bar"]*} won't work, you need to use: #}
{*context["foo:bar"]*}
# context中不建议设置的key
___、context、echo、include
layout、blocks、template、render
配置指令
模板文件目录
template_root ==> set $template_root /templates
template_location ==> set $template_location /templates
# lua-resty-template 2.x 设置root、location
local template = require "resty.template".new({
root = "/templates",
location = "/templates"
})
If none of these are set in Nginx configuration,
ngx.var.document_root (aka root-directive) value is used.
* template_root、template_location都没有设置,使用root目录
If template_location is set, it will be used first, and if
the location returns anything but 200 as a status code, we do
fallback to either template_root (if defined) or document_root
* 如果设置了template_location,优先使用template_location
* 如果template_location没有找到模版,使用template_root、root目录
示例:使用项目根路径
http {
server {
location / {
root html;
content_by_lua '
local template = require "resty.template"
template.render("view.html", { message = "Hello, World!" })
';
}
}
}
示例:使用template_root
http {
server {
set $template_root /usr/local/openresty/nginx/html/templates;
location / {
root html;
content_by_lua '
local template = require "resty.template"
template.render("view.html", { message = "Hello, World!" })
';
}
}
}
示例:使用template_location
http {
server {
set $template_location /templates;
location / {
root html;
content_by_lua '
local template = require "resty.template"
template.render("view.html", { message = "Hello, World!" })
';
}
}
}
lua api
template.root:设置模板文件位置
You can setup template root by setting this variable
which will be looked for template files
* 设置模板文件位置
This property overrides the one set in Nginx configuration
(set $template_root /my-templates;)
* 会覆盖set $template_root /my-templates的属性值
# 示例
local template = require "resty.template".new({
root = "/templates"
})
template.render_file("test.html")
template.location:设置模板文件位置
This is what you can use with OpenResty as that will
use ngx.location.capture to fetch templates files in non-blocking fashion
* 设置模板文件位置
This property overrides the one set in Nginx configuration
(set $template_location /my-templates;)
* 会覆盖set $template_location /my-templates;设置的值
# 示例
local template = require "resty.template".new({
location = "/templates"
})
template.render_file("test.html")
template.new:新建模板对象
语法格式:template.new(view, layout)
Creates a new template instance that is used as a (default) context
when rendered. A table that gets created has only one method render,
but the table also has metatable with __tostring defined. See the
example below. Both view and layout arguments can either be strings
or file paths, but layout can also be a table created previously
with template.new.
* 创建模板对象
* view:可为字符串、文件
* layout:可为字符串、文件、table
With 2.0 the new can also be used without arguments, which creates
a new template instance
* 2.0版本还可以不用参数,创建模板对象
This is handy as the template created by new does not share the
cache with the global template returned by require "resty.template"
* 使用new创建的模板对象不会和全局模板对象共享缓存
You can also pass a boolean true or false as a view parameter which
means that either safe or un-safe version of template is returned
* 可以使用true、false作为view参数,表示安全、非安全版本的模板对象
safe version uses return nil, err Lua error handling pattern and
unsafe just throws the errors, which you can catch with pcall,
xpcall or coroutine.wrap
* safe版本的模板对象返回nil、lua错误信息
* unsafe版本的模板对象直接抛出异常
# 示例:无参数创建模板对象
local template = require "resty.template".new()
# 示例:使用table创建模板对象
local config = {
root = "/templates"
}
local template = require "resty.template".new(config)
# 示例:创建安全模板对象
local unsafe = require "resty.template"
local safe = unsafe.new(true)
# 示例:创建安全模板对象
local safe = require "resty.template.safe"
local safe_instance = safe.new()
# 示例:字符串、模板文件创建模板对象
local view = template.new("template.html") --view模板文件
local view = template.new("view.html", "layout.html") --view、layout模板文件
local view = template.new[[<h1>{
{message}}</h1>]] --字符串view
local view = template.new([[<h1>{
{message}}</h1>]], [[ --字符串view、字符串layout
<html>
<body>
{*view*}
</body>
</html>
]])
template.cache:模板缓存
This function enables or disables template caching, or if
no parameters are passed, returns current state of template
caching. By default template caching is enabled, but you may
want to disable it on development or low-memory situations
* 开启、禁用模板缓存,默认开启缓存
* 如果没有参数,表示获取当前模板的缓存状态
* 开发、内存不足的时候,建议禁用缓存
Please note that if the template was already cached when
compiling a template, the cached version will be returned.
You may want to flush cache with template.cache = {} to
ensure that your template really gets recompiled
* 编译模板时,如果已经缓存了模板,会返回缓存的模板
* 可使用template.cache = {}清空缓存
# 示例
local template = require "resty.template"
local enabled = template.caching() -- 获取当前模板对象的缓存状态
template.caching(false) -- 禁用缓存
template.caching(true) -- 开启缓存
template.compile:编译模板
# 语法格式:function, boolean = template.compile(view, cache_key, plain)
* 返回函数、boolean值(表示函数是否被缓存)
function, boolean = template.compile_string(view, cache_key)
==> template.compile(view, cache_key, true)
function, boolean = template.compile_file(view, cache_key)
==> template.compile(view, cache_key, false)
Parses, compiles and caches (if caching is enabled) a template and
returns the compiled template as a function that takes context as
a parameter and returns rendered template as a string.
* 解析、编译、缓存模板,返回编译后的模板对象
* compiled template以函数形式返回
* rendered template以字符串形式返回
Optionally you may pass cache_key that is used as a cache key.
If cache key is not provided view will be used as a cache key.
If cache key is no-cache the template cache will not be checked
and the resulting function will not be cached.
* 可以提供一个缓存key,如果没有提供缓存key,view会被当作缓存key
* 如果cache key是no-cache,模板不会被缓存,结果函数也不会被缓存
You may also optionally pass plain with a value of true if the
view is plain text string (this will skip template.load and
binary chunk detection in template.parse phase). If plain is
false the template is considered to be a file, and all the
issues with file reading are considered as errors.
* plain为true,处理字符串,在解析阶段会跳过加载、检测
* plain为false,处理文件,会处理所有文件读取错误
If the plain is set to nil (the default) the template does not
consider file reading errors as fatal, and returns back the view
(usually the path of the template)
* plain设置为nil(默认),template不会处理文件读取错误,会返回view
# 示例
local func = template.compile("template.html") --模板文件
local func = template.compile([[<h1>{
{message}}</h1>]]) --字符串
local template = require "resty.template"
local func = template.compile("view.html") -- template.compile返回函数
local world = func{ message = "Hello, World!" }
local universe = func{ message = "Hello, Universe!" }
print(world, universe)
template.visit:注册访问函数
边栏推荐
- 知识分享|如何设计有效的帮助中心,不妨来看看以下几点
- 【2022杭电多校5 1003 Slipper】多个超级源点+最短路
- Pinduoduo open platform order information query interface [pdd.order.basic.list.get order basic information list query interface (according to transaction time)] code docking tutorial
- 暴雨中的人
- 立即升级!WPS Office 出现 0day 高危安全漏洞:可完全接管系统,官方推出紧急更新
- 数电快速入门(三)(卡诺图化简法的介绍)
- 如何最简单、通俗地理解爬虫的Scrapy框架?
- matlab drawing
- dotnet enables JIT multi-core compilation to improve startup performance
- Moke, dynamic image resource package display
猜你喜欢
Re24:读论文 IOT-Match Explainable Legal Case Matching via Inverse Optimal Transport-based Rationale Ext
立即升级!WPS Office 出现 0day 高危安全漏洞:可完全接管系统,官方推出紧急更新
如何一键重装Win11系统 一键重装系统方法
3、IO流之字节流和字符流
C language knowledge (1) - overview of C language, data types
LayaBox---TypeScript---Problems encountered at first contact
数电快速入门(五)(编码器的介绍以及通用编码器74LS148和74LS147的介绍)
Spss-系统聚类软件实操
二叉搜索树解决硬木问题
动手学深度学习_NiN
随机推荐
LayaBox---TypeScript---结构
AtCoder Beginner Contest 262 D - I Hate Non-integer Number
laravel whereDoesntHave
matlab drawing
Chapter7 : Network-Driven Drug Discovery
visual studio 2015 warning MSB3246
jekyll 在博客添加流程图
括号匹配
Yolov7:Trainable bag-of-freebies sets new state-of-the-art for real-time objectdetectors
动手学深度学习_NiN
【PCBA方案设计】握力计方案
LayaBox---TypeScript---首次接触遇到的问题
实战:10 种实现延迟任务的方法,附代码!
dotnet 通过 WMI 获取系统安装软件
JWT actively checks whether the Token has expired
PRIMAL: Pathfinding via Reinforcement and Imitation Multi-Agent Learning Code Analysis
2022年江苏省大学生电子设计竞赛(TI杯)B题 飞机 省级一等奖记录 “一个摆烂人的独白”
PyTorch Geometric (PyG) 安装教程
88. (the home of cesium) cesium polymerization figure
【Programming Ideas】