lua-web快速开发指南5-利用template库构建httpd模板引擎

介绍template模板引擎是为了使用户界面与业务数据(内容)分离而产生的, 其本身并不是一种深奥的技术. template模板引擎首先会将合法的模板编译为lua函数, 然后将模板文件和数据通过模板引擎生成一份HTML代码. cf的admin库整使使用了template来构建服务端渲染页面, 并利用单页面+iframe模式快速完成lua后台开发. 1. template基础语法在真正使用之前, 我们先来学习一下template常见的一些基本语法: {{ lua expression }} - lua expression是一段lua表达式; 作用为输出表达式的结果, 一些特殊符号将会被转义;{* lua expression *} - lua expression是一段lua表达式; 作用为输出表达式的结果, 不会转义任何符号;{% lua code %} - 执行一段lua代码, 如: {% for i = x, y do %} ... {% end %};{# comments #}- comments仅作为注释, 不会包含在输出字符串内. 这段语法的作用类似lua内的--与--[[]];{(template)} - 导入其它模板文件; 同时支持传参: {(file.html, { message = "Hello, World" })};2. 转义字符& 将会转义为 &amp;< 将会转义为 &lt;> 将会转义为 &gt;" 将会转义为 &quot;' 将会转义为 &#39;/ 将会转义为 &#47;3. APItemplate.compile(html)参数html为字符串类型, 可以是:模板文件路径、 ...

June 14, 2019 · 2 min · jiezi

Go-htmltemplate-模板的使用实例

从字符串载入模板我们可以定义模板字符串,然后载入并解析渲染: template.New(tplName string).Parse(tpl string) // 从字符串模板构建tplStr := ` {{ .Name }} {{ .Age }}`// if parse failed Must will render a panic errortpl := template.Must(template.New("tplName").Parse(tplStr))tpl.Execute(os.Stdout, map[string]interface{}{Name: "big_cat", Age: 29})从文件载入模板模板语法模板文件,建议为每个模板文件显式的定义模板名称:{{ define "tplName" }},否则会因模板对象名与模板名不一致,无法解析(条件分支很多,不如按一种标准写法实现),另展示一些基本的模板语法。 使用 {{ define "tplName" }} 定义模板名使用 {{ template "tplName" . }}引入其他模板使用 . 访问当前数据域:比如range里使用.访问的其实是循环项的数据域使用 $. 访问绝对顶层数据域views/header.html{{ define "header" }}<!doctype html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>{{ .PageTitle }}</title></head>{{ end }}views/footer.html{{ define "footer" }}</html>{{ end }}views/index/index.html{{ define "index/index" }} {{/*引用其他模板 注意后面的 . */}} {{ template "header" . }} <body> <div> hello, {{ .Name }}, age {{ .Age }} </div> </body> {{ template "footer" . }}{{ end }}views/news/index.html{{ define "news/index" }} {{ template "header" . }} <body> {{/* 页面变量定义 */}} {{ $pageTitle := "news title" }} {{ $pageTitleLen := len $pageTitle }} {{/* 长度 > 4 才输出 eq ne gt lt ge le */}} {{ if gt $pageTitleLen 4 }} <h4>{{ $pageTitle }}</h4> {{ end }} {{ $c1 := gt 4 3}} {{ $c2 := lt 2 3 }} {{/*and or not 条件必须为标量值 不能是逻辑表达式 如果需要逻辑表达式请先求值*/}} {{ if and $c1 $c2 }} <h4>1 == 1 3 > 2 4 < 5</h4> {{ end }} <div> <ul> {{ range .List }} {{ $title := .Title }} {{/* .Title 上下文变量调用 func param1 param2 方法/函数调用 $.根节点变量调用 */}} <li>{{ $title }} -- {{ .CreatedAt.Format "2006-01-02 15:04:05" }} -- Author {{ $.Author }}</li> {{end}} </ul> {{/* !empty Total 才输出*/}} {{ with .Total }} <div>总数:{{ . }}</div> {{ end }} </div> </body> {{ template "footer" . }}{{ end }}template.ParseFiles手动定义需要载入的模板文件,解析后制定需要渲染的模板名news/index。 ...

May 28, 2019 · 3 min · jiezi