Golang模板中使用if语句时遇到的错误
Golang模板中使用if语句时遇到的错误 在主模板中,我调用了子模板:
<div id="nav">
{{template "nav" ("posts")}}
</div>
在子模板中,我有以下 if 语句:
{{if eq . "posts"}}
<a href="/posts" class="btn active"><img src="icn/post.svg"><p>test</p></a>
{{else}}
<a href="/posts" class="btn"><img src="icn/post.svg"></a>
{{end}}
但在执行时出现错误:
template: nav.html:3:5: executing “nav” at <eq . “posts”>: error calling eq: invalid type for comparison
我做错了什么?参数 “post” 已传递给子模板,并且在子模板中可见。
先谢了。
更多关于Golang模板中使用if语句时遇到的错误的实战教程也可以访问 https://www.itying.com/category-94-b0.html
3 回复
NobbZ:
对我来说是有效的…
是的,它确实有效。问题在于我调用了另一个没有参数的“nav”。
谢谢!
问题在于 eq 函数在比较时要求两个参数类型完全一致。你传递的字符串 "posts" 是字符串类型,但模板参数 . 在子模板中可能被包装成了其他类型(比如切片或数组)。
解决方案:
方案1:使用索引访问(如果参数是切片)
<div id="nav">
{{template "nav" (slice "posts")}}
</div>
{{/* 子模板中 */}}
{{if eq (index . 0) "posts"}}
<a href="/posts" class="btn active"><img src="icn/post.svg"><p>test</p></a>
{{else}}
<a href="/posts" class="btn"><img src="icn/post.svg"></a>
{{end}}
方案2:传递单个字符串参数
<div id="nav">
{{template "nav" "posts"}}
</div>
{{/* 子模板中保持不变 */}}
{{if eq . "posts"}}
<a href="/posts" class="btn active"><img src="icn/post.svg"><p>test</p></a>
{{else}}
<a href="/posts" class="btn"><img src="icn/post.svg"></a>
{{end}}
方案3:使用结构体传递数据
<div id="nav">
{{template "nav" (dict "Page" "posts")}}
</div>
{{/* 子模板中 */}}
{{if eq .Page "posts"}}
<a href="/posts" class="btn active"><img src="icn/post.svg"><p>test</p></a>
{{else}}
<a href="/posts" class="btn"><img src="icn/post.svg"></a>
{{end}}
方案4:调试查看实际类型
{{/* 在子模板中添加调试信息 */}}
Type: {{printf "%T" .}}
Value: {{.}}
{{if eq . "posts"}}
<a href="/posts" class="btn active"><img src="icn/post.svg"><p>test</p></a>
{{else}}
<a href="/posts" class="btn"><img src="icn/post.svg"></a>
{{end}}
最常见的情况是:("posts") 这种语法创建了一个切片而不是单个字符串。使用方案2的 "posts"(不加括号)或方案1的 (slice "posts") 都能解决问题。

