### Basic Lua Server Page (LSP) Example with Layout
Source: https://github.com/bungle/lua-resty-template/blob/master/README.md
An example of an index.lsp file demonstrating the use of layouts and local Lua variables within a template. The `layout` variable specifies a default layout file to be used for rendering.
```html+lua
{%
layout = "layouts/default.lsp"
local title = "Hello, World!"
%}
{{title}}
```
--------------------------------
### Install lua-resty-template using LuaRocks
Source: https://github.com/bungle/lua-resty-template/blob/master/README.md
Installs the lua-resty-template library using LuaRocks, a package manager for Lua. This command fetches and installs the library from the LuaRocks repository.
```Shell
luarocks install lua-resty-template
```
--------------------------------
### Execute Lua Resty Template Microbenchmark via Command Line
Source: https://github.com/bungle/lua-resty-template/blob/master/README.md
This example shows how to execute the lua-resty-template microbenchmark directly from the command line using LuaJIT. It's a concise way to trigger the benchmark without modifying existing scripts.
```bash
-e 'require "resty.template.microbenchmark".run()'
```
--------------------------------
### Hello World Example with lua-resty-template
Source: https://github.com/bungle/lua-resty-template/blob/master/README.md
Demonstrates basic usage of lua-resty-template for rendering a simple HTML template with a message. It shows how to load the template library, create a template view, set variables, and render the output. It also illustrates rendering directly from a template string.
```lua
local template = require "resty.template" -- OR
local template = require "resty.template.safe" -- return nil, err on errors
-- Using template.new
local view = template.new "view.html"
view.message = "Hello, World!"
view:render()
-- Using template.render
template.render("view.html", { message = "Hello, World!" })
-- Using template string
template.render([[
{{message}}
]], { message = "Hello, World!" })
```
--------------------------------
### Install lua-resty-template using opm
Source: https://github.com/bungle/lua-resty-template/blob/master/README.md
Installs the lua-resty-template library using the OpenResty Package Manager (opm). This is a convenient way to manage dependencies for OpenResty projects.
```Shell
opm get bungle/lua-resty-template
```
--------------------------------
### LSP with Context Variable for Layout
Source: https://github.com/bungle/lua-resty-template/blob/master/README.md
This LSP example shows how to pass variables to the layout by modifying the `context` table. It demonstrates dynamic title generation by concatenating a prefix with a local variable.
```html+lua
{%
layout = "layouts/default.lsp"
local title = "Hello, World!"
context.title = 'My Application - ' .. title
%}
{{title}}
```
--------------------------------
### Rendering HTML with Template Helpers in Lua
Source: https://github.com/bungle/lua-resty-template/blob/master/README.md
Shows a practical example of using lua-resty-template with helper functions defined in a separate module (`resty.template.html`). This snippet generates an HTML unordered list and a table, demonstrating how to iterate over data and apply formatting functions within the template.
```lua
local template = require "resty.template"
local html = require "resty.template.html"
template.render([[
{% for _, person in ipairs(context) do %}
{*html.li(person.name)*}
{% end %}
{% for _, person in ipairs(context) do %}
{*html.td{ id = person.id }(person.name)*}
{% end %}
]], {
{ id = 1, name = "Emma"},
{ id = 2, name = "James" },
{ id = 3, name = "Nicholas" },
{ id = 4 }
})
```
--------------------------------
### HTML Template Structure for lua-resty-template
Source: https://github.com/bungle/lua-resty-template/blob/master/README.md
An example of a basic HTML file structure used with lua-resty-template. This file defines the layout and uses double curly braces `{{variable}}` to denote placeholders for dynamic content that will be injected during rendering.
```html
{{message}}
```
--------------------------------
### Register Template Parser Visitors in Lua
Source: https://github.com/bungle/lua-resty-template/blob/master/README.md
Demonstrates how to register visitor functions to intercept and modify template content during parsing. Visitors are executed in registration order and can inspect content type and name. The example shows a visitor that trims whitespace and logs details about template elements.
```lua
local template = require "resty.template.safe".new()
local i = 0
template.visit(function(content, type, name)
local trimmed = content:gsub("^%s+", ""):gsub("%s+$", "")
if trimmed == "" then return content end
i = i + 1
print(" visit: ", i)
if type then print(" type: ", type) end
if name then print(" name: ", name) end
print("content: ", trimmed)
print()
return content
end)
local func = template.compile([[
How are you, {{user.name}}?
Here is a new cooking recipe for you!
{% for i, ingredient in ipairs(ingredients) do %}
{*i*}. {{ingredient}}
{% end %}
{-ad-}`lua-resty-template` the templating engine for OpenResty!{-ad-}
]])
local content = func{
user = {
name = "bungle"
},
ingredients = {
"potatoes",
"sausages"
}
}
print(content)
```
--------------------------------
### Render HTML View with Blocks in Lua
Source: https://github.com/bungle/lua-resty-template/blob/master/README.md
Shows how to use blocks within HTML templates for modular content insertion, managed by Lua. This example defines a view with a main content area and an 'aside' block, which are then placed into specific locations within a layout. The layout conditionally renders the 'aside' block if it exists.
```lua
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()
```
--------------------------------
### Custom Output Function for lua-resty-template
Source: https://github.com/bungle/lua-resty-template/blob/master/README.md
Demonstrates how to override the default `template.print` function to customize output behavior. This example appends a comment to the output and uses the standard `print` function. It's useful for integrating with other frameworks or adding custom logging.
```lua
local template = require "resty.template"
template.print = function(s)
print(s)
print("")
end
```
--------------------------------
### HTML Page Template with Inheritance and Blocks
Source: https://github.com/bungle/lua-resty-template/blob/master/README.md
An example of an HTML page template that utilizes layout inheritance and defines content for specific blocks. It specifies `layout2.html` as its parent layout and provides content for `sidebar`, `content`, `page_css`, and `page_js` blocks.
```html
{% layout = "layout2.html" %}
{-sidebar-}
this is sidebar
{-sidebar-}
{-content-}
this is content
{-content-}
{-page_css-}
{-page_css-}
{-page_js-}
{-page_js-}
```
--------------------------------
### Template Creation and Rendering
Source: https://github.com/bungle/lua-resty-template/blob/master/README.md
This section details how to create new template instances, set context, and render templates. It covers different ways to initialize a template instance, including using file paths, strings, or existing tables, and how to handle safe and unsafe rendering.
```APIDOC
## template.new(view, layout)
### Description
Creates a new template instance that is used as a context when rendered. The instance has a `render` method and a `__tostring` metamethod. `view` and `layout` can be strings, file paths, or a previously created template table. It can also be called without arguments, or with a boolean `true`/`false` for safe/unsafe rendering.
### Method
`template.new`
### Parameters
- **view** (string | file path | boolean | table) - The view template or a boolean indicating safe/unsafe rendering.
- **layout** (string | file path | table, optional) - The layout template or a table created with `template.new`.
### Request Example
```lua
-- Using file paths
local view = template.new("template.html")
local view = template.new("view.html", "layout.html")
-- Using strings
local view = template.new([[
{{message}}
]])
local view = template.new([[
{{message}}
]], [[{*view*}]])
-- Using a config table
local config = { root = "/templates" }
local template_instance = template.new(config)
-- Safe/Unsafe rendering
local unsafe = require "resty.template"
local safe = unsafe.new(true)
-- Safe instance
local safe_instance = require "resty.template.safe".new()
```
### Usage Example
```lua
local template = require "resty.template"
local view = template.new("view.html")
view.message = "Hello, World!"
view:render()
-- Replacing context on render
view:render{ title = "Testing lua-resty-template" }
-- Including view context in replacement context
view:render(setmetatable({ title = "Testing lua-resty-template" }, { __index = view }))
-- Getting rendered template as a string
local result = tostring(view)
```
```
--------------------------------
### HTML: Recursive Template Inclusion
Source: https://github.com/bungle/lua-resty-template/blob/master/README.md
An example of a recursive template inclusion in HTML. This pattern should be avoided as it can lead to infinite rendering loops.
```html
{(view.html)}
```
--------------------------------
### Precompile Template to Binary File with lua-resty-template
Source: https://github.com/bungle/lua-resty-template/blob/master/README.md
Precompiles a template file (e.g., 'example.html') and saves the compiled output to a binary file (e.g., 'example-bin.html'). This process can improve performance and security by avoiding runtime parsing and obfuscating template logic.
```lua
local template = require "resty.template"
local compiled = template.precompile("example.html", "example-bin.html")
```
--------------------------------
### Render template using template_location in Nginx
Source: https://github.com/bungle/lua-resty-template/blob/master/README.md
Configures Nginx to use 'template_location' to capture template content via 'ngx.location.capture'. This example shows how to set the location and alias for template files.
```Nginx
http {
server {
set $template_location /templates;
location / {
root html;
content_by_lua '
local template = require "resty.template"
template.render("view.html", { message = "Hello, World!" })
';
}
location /templates {
internal;
alias html/templates/;
}
}
}
```
--------------------------------
### Load and Render Precompiled Template with lua-resty-template
Source: https://github.com/bungle/lua-resty-template/blob/master/README.md
Loads a precompiled template file (e.g., 'example-bin.html') and renders it with provided context parameters. This bypasses the template parsing step, leading to faster execution in production environments.
```lua
local template = require "resty.template"
template.render("example-bin.html", { "Jack", "Mary" })
```
--------------------------------
### Template Precompilation API
Source: https://github.com/bungle/lua-resty-template/blob/master/README.md
This section covers the process of precompiling templates into a binary format, which can improve performance and security by avoiding runtime parsing and Lua interpretation.
```APIDOC
## template.precompile(source_template, output_file)
### Description
Precompiles a given template file into a binary format and saves it to the specified output file. This process can be integrated into build scripts to optimize production deployments.
### Method
`template.precompile` (function)
### Parameters
- **source_template** (string) - The path to the template file to be precompiled.
- **output_file** (string) - The path where the precompiled binary template will be saved.
### Request Example
```lua
local template = require "resty.template"
local compiled = template.precompile("example.html", "example-bin.html")
```
### Response
- **boolean** - Returns `true` on successful precompilation.
```
```APIDOC
## Loading and Rendering Precompiled Templates
### Description
Demonstrates how to load and render a template that has already been precompiled into a binary file. This bypasses the need for runtime template parsing.
### Method
`template.render` (function, when used with precompiled files)
### Parameters
- **precompiled_template_path** (string) - The path to the precompiled binary template file.
- **context_parameters** (table) - A table containing the variables to be used when rendering the template.
### Request Example
```lua
local template = require "resty.template"
template.render("example-bin.html", { "Jack", "Mary" })
```
### Response
- **string** - The rendered output of the precompiled template.
```
--------------------------------
### Render HTML View with Layout in Lua
Source: https://github.com/bungle/lua-resty-template/blob/master/README.md
Demonstrates how to create and render an HTML view using a specified layout in Lua. It involves initializing a template object with view and layout files, setting dynamic variables, and then rendering the final HTML. Dependencies include the lua-resty-template library.
```lua
local view = template.new("view.html", "layout.html")
view.title = "Testing lua-resty-template"
view.message = "Hello, World!"
view:render()
```
--------------------------------
### Create New Template Instance with Layouts (Lua)
Source: https://context7.com/bungle/lua-resty-template/llms.txt
Creates a new template instance for reusable context. Supports views with layouts, separating content from master structure. Provides `render` and `process` methods.
```lua
local template = require "resty.template"
-- Create view with layout
local page = template.new("content.html", "layout.html")
page.title = "My Page Title"
page.content = "This is the page content"
page:render()
-- Using inline strings for view and layout
local view = template.new([[
--
-- Get rendered content as string
local result = tostring(view)
```
--------------------------------
### Render Template from File with Context
Source: https://context7.com/bungle/lua-resty-template/llms.txt
Renders a template from a specified file path. It requires setting a `template.root` directory. File I/O errors are treated as assertion errors. This is preferred for file-based templates.
```lua
local template = require "resty.template"
-- Set root directory for templates
template.root = "/var/www/templates"
-- Render a template file with context
template.render_file("welcome.html", {
username = "John",
logged_in = true
})
```
--------------------------------
### HTML: Including Templates from Subdirectories
Source: https://github.com/bungle/lua-resty-template/blob/master/README.md
Shows how to include template files located in subdirectories using the `{(syntax)}` tag. The path is relative to the template loading path.
```html
{(users/list.html)}
```
--------------------------------
### Layouts with Views in Lua
Source: https://github.com/bungle/lua-resty-template/blob/master/README.md
Explains how to implement master pages or layouts in lua-resty-template. It shows multiple ways to define and render views within a layout, allowing for consistent structure across multiple pages. This includes compiling views and assigning them to layout properties.
```lua
local template = require "resty.template"
local layout = template.new "layout.html"
layout.title = "Testing lua-resty-template"
layout.view = template.compile "view.html" { message = "Hello, World!" }
layout:render()
-- Or like this
template.render("layout.html", {
title = "Testing lua-resty-template",
view = template.compile "view.html" { message = "Hello, World!" }
})
-- Or maybe you like this style more
-- (but please remember that context.view is overwritten on rendering the layout.html)
local view = template.new("view.html", "layout.html")
view.title = "Testing lua-resty-template"
view.message = "Hello, World!"
view:render()
-- Well, maybe like this then?
local layout = template.new "layout.html"
layout.title = "Testing lua-resty-template"
local view = template.new("view.html", layout)
view.message = "Hello, World!"
view:render()
```
--------------------------------
### Template Loading API
Source: https://github.com/bungle/lua-resty-template/blob/master/README.md
This section details the functions used for loading templates, including default loaders for Lua and Nginx/OpenResty, and how to provide custom loaders.
```APIDOC
## template.load(view, plain)
### Description
This function is used to load templates. It is called by `template.parse` before parsing begins, unless the `plain` argument is true. Default loaders for Lua and Nginx/OpenResty are provided, and users can supply their own custom loader functions, for example, to load templates from a database.
### Method
`template.load` (function)
### Parameters
- **view** (string) - The template identifier (e.g., file path or name).
- **plain** (boolean, optional) - If true, the `view` is treated as the template content directly. Defaults to `nil`.
### Request Example (Lua Default Loader)
```lua
function(view, plain)
if plain == true then return view end
local path, root = view, template.root
if root and root ~= EMPTY then
if byte(root, -1) == SOL then root = sub(root, 1, -2) end
if byte(view, 1) == SOL then path = sub(view, 2) end
path = root .. "/" .. path
end
return plain == false and assert(read_file(path)) or read_file(path) or view
end
```
### Request Example (Nginx/OpenResty Default Loader)
```lua
function(view, plain)
if plain == true then return view end
local vars = VAR_PHASES[phase()]
local path = view
local root = template.location
if (not root or root == EMPTY) and vars then
root = var.template_location
end
if root and root ~= EMPTY then
if byte(root, -1) == SOL then root = sub(root, 1, -2) end
if byte(path, 1) == SOL then path = sub(path, 2) end
path = root .. "/" .. path
local res = capture(path)
if res.status == 200 then return res.body end
end
path = view
root = template.root
if (not root or root == EMPTY) and vars then
root = var.template_root
if not root or root == EMPTY then root = var.document_root or prefix end
end
if root and root ~= EMPTY then
if byte(root, -1) == SOL then root = sub(root, 1, -2) end
if byte(path, 1) == SOL then path = sub(path, 2) end
path = root .. "/" .. path
end
return plain == false and assert(read_file(path)) or read_file(path) or view
end
```
### Request Example (Custom Loader - Redis)
```lua
local template = require "resty.template"
template.load = function(view, plain) return view end
```
### Response
- **string** - The loaded template content.
### Response Example
```json
"Hello, {{name}}!"
```
### Error Handling
If `plain` is `false` and file I/O issues occur, they are treated as assertion errors.
```
```APIDOC
## template.load_string(view)
### Description
This is a convenience function that simply calls `template.load(view, true)`, treating the provided `view` argument directly as the template string content.
### Method
`template.load_string` (function)
### Parameters
- **view** (string) - The template content as a string.
### Response
- **string** - The template content.
### Response Example
```json
"Hello, {{name}}!"
```
```
```APIDOC
## template.load_file(view)
### Description
This is a convenience function that calls `template.load(view, false)`, ensuring that the provided `view` argument is treated as a file path and attempting to load the template content from that file. File I/O errors will result in assertion errors.
### Method
`template.load_file` (function)
### Parameters
- **view** (string) - The path to the template file.
### Response
- **string** - The content of the template file.
### Response Example
```json
"Hello, {{name}}!"
```
```
```APIDOC
## template.print
### Description
This field holds the function used for outputting the results of `template.render()` or `template.new(...):render()`. By default, it is set to `ngx.print` if available, otherwise it falls back to the standard Lua `print` function. This field can be overwritten to use a custom output function, which is useful for integration with other frameworks or custom logging.
### Method
`template.print` (function)
### Parameters
- **s** (string) - The string content to be outputted.
### Request Example (Custom Output Function)
```lua
local template = require "resty.template"
template.print = function(s)
print(s)
print("")
end
```
### Response
Outputs the provided string `s` using the assigned function.
```
--------------------------------
### Configure template root and location in Lua
Source: https://github.com/bungle/lua-resty-template/blob/master/README.md
Demonstrates how to programmatically override the template root and location settings within Lua code. This allows for dynamic configuration of template paths.
```Lua
local template = require "resty.template".new({
root = "/templates",
location = "/templates"
})
```
--------------------------------
### Include Views in Lua
Source: https://github.com/bungle/lua-resty-template/blob/master/README.md
Illustrates how to include one template within another using the `{(template)}` and `{(template, context)}` syntax. This allows for modular template design, where a main template can incorporate content from other files, optionally passing a specific context.
```lua
local template = require "resty.template"
template.render("include.html", { users = {
{ name = "Jane", age = 29 },
{ name = "John", age = 25 }
}})
```
--------------------------------
### Alternative Lua Configuration for Template Root and Location (Lua)
Source: https://context7.com/bungle/lua-resty-template/llms.txt
Provides an alternative method to configure the template root and location using Lua code directly, instead of Nginx variables. This approach uses `template.new` to create a reusable template object.
```lua
-- Alternative: Configure root and location in Lua
local template = require "resty.template".new({
root = "/var/www/templates",
location = "/templates"
})
template.render_file("page.html", { title = "My Page" })
```
--------------------------------
### Create New Template Instance with Lua Resty Template
Source: https://github.com/bungle/lua-resty-template/blob/master/README.md
Creates a new template instance used as a context for rendering. Arguments can be strings, file paths, or previously created template tables. It supports safe and unsafe modes, and allows for custom configuration.
```lua
local template = require "resty.template".new()
local config = {
root = "/templates"
}
local template = require "resty.template".new(config)
local unsafe = require "resty.template"
local safe = unsafe.new(true)
local safe_instance = require "resty.template.safe".new()
local view = template.new"template.html"
local view = template.new("view.html", "layout.html")
local view = template.new[[
{{message}}
]]
local view = template.new([[
{{message}}
]], [[
{*view*}
]])
```
--------------------------------
### Default Layout for Lua Server Pages (LSP)
Source: https://github.com/bungle/lua-resty-template/blob/master/README.md
This file defines the default layout structure for LSP templates. It includes a header and a placeholder for the view content, demonstrating how to structure reusable page elements.
```html+lua
{(include/header.lsp)}
{*view*}
```
--------------------------------
### Precompile Templates to Bytecode (Lua)
Source: https://context7.com/bungle/lua-resty-template/llms.txt
Precompiles a template into a binary Lua bytecode chunk for disk saving and later loading. This optimizes performance by skipping runtime parsing and compilation.
```lua
local template = require "resty.template"
local view = [[
{{title}}
{% for _, item in ipairs(items) do %}
{{item}}
{% end %}
]]
-- Precompile and save to file
template.precompile(view, "precompiled.bin")
-- Or get the bytecode without saving
local bytecode = template.precompile(view)
-- Later, use the precompiled template
template.render("precompiled.bin", {
title = "My List",
items = { "One", "Two", "Three" }
})
```
--------------------------------
### Header Include for Lua Server Pages (LSP)
Source: https://github.com/bungle/lua-resty-template/blob/master/README.md
A simple include file for LSP templates that contains the HTML head section, including the page title. This demonstrates how to include reusable header content in templates.
```html
Testing Lua Server Pages
```
--------------------------------
### Safe Mode Compilation and Rendering with Error Handling (Lua)
Source: https://context7.com/bungle/lua-resty-template/llms.txt
Demonstrates how to use the safe template module for compiling and rendering templates with explicit error handling. It returns nil, error instead of throwing exceptions, making it suitable for production.
```lua
local template = require "resty.template.safe"
-- Compile with error handling
local func, err = template.compile("{{invalid syntax")
if not func then
print("Compilation error:", err)
end
-- Render with error handling
local ok, render_err = template.render([[
{{title}}
{% for _, item in ipairs(items) do %}
{{item}}
{% end %}
]], { title = "Test" }) -- items is nil, would normally error
if not ok then
print("Render error:", render_err)
end
-- Process with error handling
local result, process_err = template.process("{{message}}", { message = "Hello" })
if result then
print(result) -- Output: Hello
else
print("Process error:", process_err)
end
```
--------------------------------
### Render Template to Output in Lua
Source: https://github.com/bungle/lua-resty-template/blob/master/README.md
Demonstrates the `template.render` function, which parses, compiles, and outputs a template directly. It uses `ngx.print` if available, otherwise falls back to `print`. Similar to `template.process`, it accepts a view (string or file), context, and optional cache key. The `plain` argument differentiates between string and file templates.
```lua
template.render("template.html", { message = "Hello, World!" }) -- or
template.render([[
{{message}}
]], { message = "Hello, World!" })
```
--------------------------------
### Precompile Template to Binary Chunk with lua-resty-template
Source: https://github.com/bungle/lua-resty-template/blob/master/README.md
Precompiles a template into a binary chunk, which can be saved to a file or loaded directly. The 'plain' parameter determines if the view is treated as a string or file path. Errors during file I/O when 'plain' is false will cause an assertion failure.
```lua
local view = [[
{{title}}
{% for _, v in ipairs(context) do %}
{{v}}
{% end %}
]]
local compiled = template.precompile(view)
local file = io.open("precompiled-bin.html", "wb")
file:write(compiled)
file:close()
-- Alternatively you could just write (which does the same thing as above)
template.precompile(view, "precompiled-bin.html")
template.render("precompiled-bin.html", {
title = "Names",
"Emma", "James", "Nicholas", "Mary"
})
```
--------------------------------
### Use Blocks with Layouts for Content Injection (Lua)
Source: https://context7.com/bungle/lua-resty-template/llms.txt
Blocks allow moving content from a view to specific placeholders in a layout, enabling flexible page composition where views inject content into multiple layout locations.
```lua
local template = require "resty.template"
-- view.html content:
--
{{message}}
-- {-sidebar-}
--
-- {% for _, item in ipairs(menu) do %}
--
{{item}}
-- {% end %}
--
-- {-sidebar-}
-- layout.html content:
--
--
-- {{title}}
--
-- {*view*}
-- {% if blocks.sidebar then %}
--
-- {% end %}
--
--
local page = template.new("view.html", "layout.html")
page.title = "My Page"
page.message = "Hello, World!"
page.menu = { "Home", "About", "Contact" }
page:render()
```
--------------------------------
### template.process
Source: https://context7.com/bungle/lua-resty-template/llms.txt
Parses, compiles, caches, and returns the rendered template as a string instead of printing it. This is useful when you need to capture the output for further processing.
```APIDOC
## template.process
### Description
Parses, compiles, caches and returns the rendered template as a string instead of printing it. This is useful when you need to capture the output for further processing, such as sending emails or storing in a cache.
### Method
`template.process(template_string_or_path, context)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```lua
local template = require "resty.template"
-- Process template and get result as string
local html = template.process([[
{{product.name}}
{{product.description}}
{*product.price*}
]], {
product = {
name = "Premium Widget",
description = "A high-quality widget for all your needs",
price = "99.99"
}
})
-- html now contains the rendered string
print(html)
```
### Response
#### Success Response (200)
Returns the rendered template as a string.
#### Response Example
```html
Premium Widget
A high-quality widget for all your needs
99.99
```
```
--------------------------------
### Configure Nginx for Lua Server Pages (LSP) with OpenResty
Source: https://github.com/bungle/lua-resty-template/blob/master/README.md
This Nginx configuration sets up OpenResty to process .lsp files using the lua-resty-template library. It initializes the template module and defines a location block to render LSP files as content.
```nginx
http {
init_by_lua '
require "resty.core"
template = require "resty.template"
template.caching(false); -- you may remove this on production
';
server {
location ~ \.lsp$ {
default_type text/html;
content_by_lua 'template.render(ngx.var.uri)';
}
}
}
```
--------------------------------
### Process Template and Return String
Source: https://context7.com/bungle/lua-resty-template/llms.txt
Parses, compiles, caches, and returns the rendered template as a string, rather than printing it directly. This is useful for capturing output for further processing, like sending emails.
```lua
local template = require "resty.template"
-- Process template and get result as string
local html = template.process([[
{{product.name}}
{{product.description}}
${*product.price*}
]], {
product = {
name = "Premium Widget",
description = "A high-quality widget for all your needs",
price = "99.99"
}
})
-- html now contains the rendered string
print(html)
```
--------------------------------
### HTML: Basic Template Structure
Source: https://github.com/bungle/lua-resty-template/blob/master/README.md
A basic HTML template structure demonstrating the use of template tags for including other templates, displaying variables, and executing Lua loops. Dependencies: 'header.html', 'footer.html'.
```html
{(header.html)}
{{message}}
{% for _, name in ipairs(names) do %}
{{name}}
{% end %}
{(footer.html)}
```
--------------------------------
### Lua: Render Template with Context
Source: https://github.com/bungle/lua-resty-template/blob/master/README.md
Renders a template file with provided context variables. The context can include strings, arrays, and HTML content. Dependencies: 'resty.template'.
```lua
local template = require "resty.template"
template.render("view.html", {
title = "Testing lua-resty-template",
message = "Hello, World!",
names = { "James", "Jack", "Anne" },
jquery = ''
})
```
--------------------------------
### Process Template from String or File in Lua
Source: https://github.com/bungle/lua-resty-template/blob/master/README.md
Shows how to use the `template.process` function to parse, compile, and render a template. It supports processing templates from either a file path or a raw string. The function takes the template view, a context table for variables, and an optional cache key. The `plain` argument controls whether the view is treated as a string or a file.
```lua
local output = template.process("template.html", { message = "Hello, World!" }) -- or
local output = template.process([[
{{message}}
]], { message = "Hello, World!" })
```
--------------------------------
### Run Lua Resty Template Microbenchmark
Source: https://github.com/bungle/lua-resty-template/blob/master/README.md
This code snippet demonstrates how to run the microbenchmark for lua-resty-template. It requires the 'resty.template.microbenchmark' module and can optionally accept an iteration count. The benchmark measures parsing, compilation, and execution times for templates.
```lua
local benchmark = require "resty.template.microbenchmark"
benchmark.run()
-- You may also pass iteration count (by default it is 1,000)
benchmark.run(100)
```
--------------------------------
### Compile and Render Template Function with Lua Resty Template
Source: https://github.com/bungle/lua-resty-template/blob/master/README.md
Demonstrates compiling a template and then using the returned function to render it with different contexts. The second return value of `compile` indicates if the function was cached.
```lua
local template = require "resty.template"
local func = template.compile("view.html")
local world = func{ message = "Hello, World!" }
local universe = func{ message = "Hello, Universe!" }
print(world, universe)
```
--------------------------------
### Extending Template Functionality with Moses in Lua
Source: https://github.com/bungle/lua-resty-template/blob/master/README.md
Demonstrates how to extend the capabilities of lua-resty-template by integrating external libraries like Moses. This involves adding the library to the template's environment, enabling its functions to be used directly within templates for more complex logic.
```lua
local _ = require "moses"
local template = require "resty.template"
template._ = _
```
--------------------------------
### Process Template from File in Lua
Source: https://github.com/bungle/lua-resty-template/blob/master/README.md
Provides a shortcut function `template.process_file` which is equivalent to calling `template.process` with the `plain` argument set to `false`. This is used when the template content is located in a file.
```lua
local output = template.process_file(view, context, cache_key)
```
--------------------------------
### Render Template Instance with Lua Resty Template
Source: https://github.com/bungle/lua-resty-template/blob/master/README.md
Renders a template instance with provided context. Context can be set directly on the instance or passed during the render call. The rendered output can be obtained as a string using tostring.
```lua
local template = require "resty.template"
local view = template.new"view.html"
view.message = "Hello, World!"
view:render()
view:render{ title = "Testing lua-resty-template" }
view:render(setmetatable({ title = "Testing lua-resty-template" }, { __index = view }))
local result = tostring(view)
```
--------------------------------
### Render template using document_root in Nginx
Source: https://github.com/bungle/lua-resty-template/blob/master/README.md
Configures Nginx to use the 'document_root' directive to locate template files. The 'content_by_lua' directive is used to call the template rendering function.
```Nginx
http {
server {
location / {
root html;
content_by_lua '
local template = require "resty.template"
template.render("view.html", { message = "Hello, World!" })
';
}
}
}
```
--------------------------------
### Alternative HTML Layout with Sidebar and Content
Source: https://github.com/bungle/lua-resty-template/blob/master/README.md
Presents an alternative HTML layout structure, also extending a base layout. It features distinct styling for sidebar and content areas compared to `layout1.html`, demonstrating flexibility in defining page structures while reusing a common base.
```html
{% layout = "base.html" %}
{-main-}
{* blocks.sidebar *}
{* blocks.content *}
I am different from layout1
{-main-}
```
--------------------------------
### Render Template from String
Source: https://context7.com/bungle/lua-resty-template/llms.txt
Renders a template directly from a string, bypassing file loading. This is useful for templates stored in databases or generated dynamically. It takes the template string and a context table.
```lua
local template = require "resty.template"
local email_template = [[
Dear {{recipient}},
Thank you for your order #{{order_id}}.
Items:
{% for _, item in ipairs(items) do %>
- {{item.name}}: ${{item.price}}
{% end %}
Total: ${{total}}
Best regards,
{{company}}
]]
template.render_string(email_template, {
recipient = "Jane Smith",
order_id = "12345",
items = {
{ name = "Widget", price = "19.99" },
{ name = "Gadget", price = "29.99" }
},
total = "49.98",
company = "Acme Corp"
})
```
--------------------------------
### Handle Runtime Errors with Visitors in Lua
Source: https://github.com/bungle/lua-resty-template/blob/master/README.md
Illustrates using a visitor function to gracefully handle runtime errors in template expressions, specifically when variables are undefined. The visitor intercepts expressions of type '*' or '{' and wraps them in a pcall to safely evaluate them, returning an empty string if an error occurs.
```lua
local template = require "resty.template".new()
template.visit(function(content, type)
if type == "*" or type == "{" then
return "select(3, pcall(function() return nil, " .. content .. " end)) or ''"
end
return content
end)
template.render "Calculation: {{i*10}}\n"
template.render("Calculation: {{i*10}}\n", { i = 1 })
```
--------------------------------
### Compile HTML Template in Lua
Source: https://github.com/bungle/lua-resty-template/blob/master/README.md
Illustrates the process of compiling an HTML template file using lua-resty-template. This is a foundational step for more complex template structures, including inheritance. The function `compile` takes the template file name and an optional table of variables.
```lua
local res = require"resty.template".compile("page.html"){}
```
--------------------------------
### HTML Layout with Content Placeholders
Source: https://github.com/bungle/lua-resty-template/blob/master/README.md
Defines a basic HTML structure for a web page, serving as a layout template. It includes a title, a main content area, and placeholders for CSS and JavaScript files. This layout is designed to be extended by other templates using block inheritance.
```html
{* blocks.page_css *}
{* blocks.main *}
{* blocks.page_js *}
```
--------------------------------
### HTML: Accessing Complex Context Keys
Source: https://github.com/bungle/lua-resty-template/blob/master/README.md
Illustrates accessing context variables with complex keys in HTML templates. It requires explicit referencing using `context["key"]` syntax.
```html
{*context["foo:bar"]*}
```
--------------------------------
### template.render_file
Source: https://context7.com/bungle/lua-resty-template/llms.txt
Renders a template from a file path. All file I/O issues are considered assertion errors. This is the preferred method when you know the template is stored in a file.
```APIDOC
## template.render_file
### Description
Renders a template from a file path, treating the view parameter strictly as a file path. All file I/O issues are considered assertion errors. This is the preferred method when you know the template is stored in a file.
### Method
`template.render_file(file_path, context)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```lua
local template = require "resty.template"
-- Set root directory for templates
template.root = "/var/www/templates"
-- Render a template file with context
template.render_file("welcome.html", {
username = "John",
logged_in = true
})
```
### Response
#### Success Response (200)
Outputs the rendered HTML directly to the standard output or `ngx.print`.
#### Response Example
Assuming `welcome.html` contains:
```html
Welcome, {{username}}!
{% if logged_in then %>
You are logged in.
{% end %}
```
Output:
```html
Welcome, John!
You are logged in.
```
```
--------------------------------
### Echo Output in Lua
Source: https://github.com/bungle/lua-resty-template/blob/master/README.md
Demonstrates the use of the `echo` function within lua-resty-template to output dynamic content, particularly useful within `{% .. %}` blocks for loops or conditional statements. It shows an alternative syntax without `echo` for comparison.
```lua
require "resty.template".render[[
begin
{%
for i=1, 10 do
echo("\tline: ", i, "\n")
end
%}
end
]]
```
```lua
require "resty.template".render[[
begin
{% for i=1, 10 do %}
line: {* i *}
{% end %}
end
]]
```
--------------------------------
### Template Compilation
Source: https://github.com/bungle/lua-resty-template/blob/master/README.md
Compile templates into functions for rendering. This covers compiling from strings or files, with options for caching and cache keys.
```APIDOC
## template.compile(view, cache_key, plain)
### Description
Parses, compiles, and optionally caches a template. Returns a compiled function that takes context and returns the rendered template string. `cache_key` can be provided for caching, and `plain` can be set to `true` if the `view` is a plain text string.
### Method
`template.compile`
### Parameters
- **view** (string | file path) - The template content or path.
- **cache_key** (string, optional) - A key for caching the compiled template. If not provided, `view` is used. Use `"no-cache"` to prevent caching.
- **plain** (boolean, optional) - If `true`, `view` is treated as a plain string, skipping file detection. Defaults to `nil`, which treats file reading errors as non-fatal.
### Request Example
```lua
-- Compile from a file
local func = template.compile("template.html")
-- Compile from a string
local func = template.compile([[
{{message}}
]])
-- Compile with a specific cache key
local func = template.compile("template.html", "my_template_key")
-- Compile as plain text
local func = template.compile([[
{{message}}
]], nil, true)
```
### Response
- **function** - A function that takes a context table and returns the rendered template string.
- **boolean** - Indicates if the returned function was cached.
### Response Example
```lua
local template = require "resty.template"
local func = template.compile("view.html")
local world = func{ message = "Hello, World!" }
local universe = func{ message = "Hello, Universe!" }
print(world, universe)
-- Output: Hello, World! Hello, Universe!
```
```
```APIDOC
## template.compile_string(view, cache_key)
### Description
Compiles a template from a string. This is a convenience function that calls `template.compile(view, cache_key, true)`.
### Method
`template.compile_string`
### Parameters
- **view** (string) - The template content as a string.
- **cache_key** (string, optional) - A key for caching the compiled template.
### Response
- **function** - A function that takes a context table and returns the rendered template string.
- **boolean** - Indicates if the returned function was cached.
```
```APIDOC
## template.compile_file(view, cache_key)
### Description
Compiles a template from a file. This is a convenience function that calls `template.compile(view, cache_key, false)`.
### Method
`template.compile_file`
### Parameters
- **view** (file path) - The path to the template file.
- **cache_key** (string, optional) - A key for caching the compiled template.
### Response
- **function** - A function that takes a context table and returns the rendered template string.
- **boolean** - Indicates if the returned function was cached.
```
--------------------------------
### Render template using template_root in Nginx
Source: https://github.com/bungle/lua-resty-template/blob/master/README.md
Configures Nginx to use the 'template_root' directive to specify the directory for template files. The 'content_by_lua' directive then renders the specified template.
```Nginx
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!" })
';
}
}
}
```
--------------------------------
### HTML Helper Module for Programmatic HTML Generation (Lua)
Source: https://context7.com/bungle/lua-resty-template/llms.txt
Utilizes the HTML helper module to programmatically generate HTML elements with automatic escaping. It provides a fluent interface for creating tags with attributes and content, and can be used within templates.
```lua
local template = require "resty.template"
local html = require "resty.template.html"
-- Simple tag with content
print(html.p("Hello, World!"))
-- Output:
Hello, World!
-- Tag with attributes
print(html.a{ href = "https://example.com", class = "link" }("Click here"))
-- Output: Click here
-- Self-closing tag
print(html.input{ type = "text", name = "username" }())
-- Output:
-- Use in templates
template.render([[
{% for _, person in ipairs(people) do %}
{*html.li{ class = "person" }(person.name)*}
{% end %}
]], {
html = html,
people = {
{ name = "Alice" },
{ name = "Bob" }
}
})
```