Revel 模板不支持嵌入 Go 代码,仅允许使用模板函数和动作;其底层基于 Go 的 html/template,故无法使用 if err != nil { ... } 或 for i := 0; i
模板里不能写 Go 代码,只能用模板函数和动作
Revel 模板底层用的是 Go
html/template,它不支持直接嵌入 Go 代码块(比如if err != nil { ... }或for i := 0; i )。所有逻辑必须通过预定义的动作(如{{if}}、{{range}})或函数(如eq、field)表达。试图写{{.User.Name.String()}}或{{len .Items}}会编译失败——因为.User.Name.String()是方法调用,len是内置函数,二者都不在 Revel 模板函数白名单中。条件判断只能用
{{if}}+ 内置函数,不能用==模板里写
{{if .Status == "active"}}会直接报错parse error in template: unexpected "=" in if。Go 模板语法禁止原生比较运算符,必须用函数:
{{if eq .Status "active"}}—— 字符串/数值相等(宽松类型转换){{if ne .Role "guest"}}—— 不等判断{{if and .IsAdmin .IsActive}}—— 多条件与{{if or .IsLoggedIn .IsDemo}}—— 多条件或注意:
eq对nil、空切片、空 map、空字符串都返回true,所以{{if eq .Tags nil}}是无效写法;应改用{{if not .Tags}}或{{if .Tags}}做存在性判断。
{{range}}遍历必须显式声明索引变量,且需防nil遍历切片时若未检查是否为
nil,模板渲染会 panic。正确写法是先{{if .Items}}再{{range}}:{{if .Items}} {{range $i, $item := .Items}} <div data-index="{{$i}}">{{.Name}}</div> {{end}} {{else}} <p>暂无数据</p><div class="aritcle_card flexRow artxards"> <div class="artcardd flexRow"> <a class="aritcle_card_img" rel="nofollow" href="/xiazai/gongju/2853" title="Revel框架 0.19.0"><img src="https://img.php.cn/upload/manual/001/589/237/6ad0beeae1170134.png" alt="Revel框架 0.19.0" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a> <div class="aritcle_card_info flexColumn"> <a rel="nofollow" href="/xiazai/gongju/2853" title="Revel框架 0.19.0" class="overflowclass">Revel框架 0.19.0</a> <p class="overflowclass">Revel框架 0.19.0 版本源码包下载,适合关注 Referrer-Policy、vendor 识别、Gorp 事务抽象和 CSRF 修复的开发团队。</p> </div> <a rel="nofollow" href="/xiazai/gongju/2853" title="Revel框架 0.19.0" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span> </a> </div> </div> {{end}}关键点:
- 索引变量名必须带
$前缀(如$i),否则可能覆盖外层同名字段(比如控制器传了.Index = 42).Name中的.在range块内自动指向当前元素(即$item),不是原始数据对象- 若需同时传索引和元素进子模板,用
{{template "item.html" dict "index" $i "item" $item}},前提是已注册dict函数嵌套结构体字段访问失败?90% 是导出问题
模板报错
company is an unexported field of struct type interface{},说明你传入的结构体字段名是小写(如type Data struct { items []item })。Go 模板只能访问首字母大写的导出字段:
- 结构体类型名必须大写:
type Item struct { Name string }- 字段名必须大写:
type Data struct { Items []Item }- 切片元素类型也必须导出,否则
{{range .Items}}{{.Name}}{{end}}中的.Name无法读取控制器里传值没问题,但模板里
.Items[0].Name为空或报错,八成是这里卡住了——别查路由或日志,先看结构体字段大小写。











