|
1 | 1 | # lua-resy-template
|
2 | 2 | Simple template engine for lua and openresty
|
3 | 3 |
|
4 |
| -# Syntax |
| 4 | +# Methods |
| 5 | + |
| 6 | +## new |
| 7 | +`syntax: t = template.new(callback, minify, tags)` |
| 8 | + |
| 9 | +create new template instance, all params is optional |
| 10 | +the default value of callback is "io.write" or "ngx.print" |
| 11 | +the default value of minify is false |
| 12 | +the default value of tags is {"{{", "}}", "{%%", "%%}"} |
| 13 | + |
| 14 | +## parse |
| 15 | +`syntax: code = t:parse(tmpl, minify)` |
| 16 | + |
| 17 | +parse the template into lua code. |
| 18 | + |
| 19 | +## compile |
| 20 | +`syntax: func = t:compile(tmpl, minify)` |
| 21 | + |
| 22 | +compile the template into lua function, this method will call parse method. |
| 23 | +this method will auto cache the compiled function. |
| 24 | + |
| 25 | +## render |
| 26 | +`syntax: t:render(tmpl_or_func, data, callback, minify)` |
| 27 | + |
| 28 | +render the template with variables stored in data, |
| 29 | +the first param can be template string or compiled function. |
| 30 | +the callback and minify params will replace the default value gived from "new" method. |
| 31 | + |
| 32 | + |
| 33 | +# Template Syntax |
5 | 34 |
|
6 | 35 | In short, statements must be included between percent signs and expressions must be placed between brackets.
|
7 | 36 |
|
@@ -30,4 +59,29 @@ variables or expressions will be replaced
|
30 | 59 |
|
31 | 60 | # Demo
|
32 | 61 |
|
33 |
| -please see detail in "test.lua" |
| 62 | +the test demo in file "test.lua" |
| 63 | + |
| 64 | + local template = require "lib.resty.template" |
| 65 | + local t = template.new() |
| 66 | + local tmpl = [[ |
| 67 | + <h1>{{title}}</h1> |
| 68 | + <h2>{{title .. " -" .. '- ' .. subtitle}}</h2> |
| 69 | + {% if messages then %} |
| 70 | + {% for i, message in ipairs(messages) do %} |
| 71 | + <p>{{message}}</p> |
| 72 | + {% end %} |
| 73 | + {% end %} |
| 74 | + {% local testvar = 'set val in template'%}{{ testvar }} |
| 75 | + ]] |
| 76 | + local data = {title = 'Title', subtitle = 'Sub Title', messages = {'test message 1', 'test message 2'}} |
| 77 | + t:render(tmpl, data) |
| 78 | + |
| 79 | +will get result: |
| 80 | + |
| 81 | + <h1>Title</h1> |
| 82 | + <h2>Title -- Sub Title</h2> |
| 83 | + <p>test message 1</p> |
| 84 | + <p>test message 2</p> |
| 85 | + set val in template |
| 86 | + |
| 87 | + |
0 commit comments