src="{{.photo}}" 会使模板崩溃,就像变量未正确传递一样。也许问题是这是在一个循环内,所以我需要每篇文章一个随机数才能显示照片?
还有其他方法可以直接在模板中执行吗?
更新
感谢我现在得到的指导
min := 1 max := 1563 photos := make([]int, len(pages)) for i := range photos { photos[i] = rand.intn(max - min + 1) } tmpl.executetemplate(w, "index.html", struct { pages []page currentpage int totalpage int nextpage int previouspage int lastpage int shownext bool showprevious bool photo []int }{ pages: pages, currentpage: pageindex + 1, totalpage: totalpaginationpage, nextpage: pageindex + 1, previouspage: pageindex - 1, lastpage: totalpaginationpage - 1, shownext: pageindex+1 < totalpaginationpage, showprevious: pageindex-1 >= 0, photo: photos, })
在模板中
{{range $idx, $page := .pages}}{{end}}
也尝试过
但不幸的是,一旦我调用,模板就会停止执行
{{index $.Photos $idx}}
我认为这是我这边的某种打字错误?
正确答案
{{range}}
操作会更改点,因此 {{range .pages}}
内的 {{.photo}}
将解析为 .pages
的元素。
使用$
来引用“外层”,传递给模板执行的原始值:
src="{{$.photo}}"
虽然这只是一个整数,但您可能希望在路径或 url 中使用它,如下所示:
src="/path/to/images?id={{$.photo}}"
注意:如果您想为所有页面使用不同的图像,则必须为每个页面传递不同的数字,而不仅仅是单个数字。然后在页面中添加一个 photo
字段,然后您可以在 {{range}}
中引用它,如原始代码中的 {{.photo}}
。
您写道,您无法修改 page
,因为它来自您的数据库。如果是这样,则传递一段随机数并使用 index
访问它们,如下所示:
min := 1 max := 1563 photos := make([]int, len(pages)) for i := range photos { photos[i] = rand.intn(max - min + 1) } tmpl.executetemplate(w, "index.html", struct { pages []page currentpage int totalpage int nextpage int previouspage int lastpage int shownext bool showprevious bool photo []int }{ pages: pages, currentpage: pageindex + 1, totalpage: totalpaginationpage, nextpage: pageindex + 1, previouspage: pageindex - 1, lastpage: totalpaginationpage - 1, shownext: pageindex+1 < totalpaginationpage, showprevious: pageindex-1 >= 0, photo: photos, })
在模板中:
{{range $idx, $page := .pages}}{{end}}
或者注册一个 random
函数,您可以从模板中调用该函数:
// parse the template as you did, but first register a random function: min, max := 1, 1563 tmpl, err := template.new("").funcs(template.funcmap{ "random": func() int { return rand.intn(max - min + 1) }, }).parsefiles("template-name.html")
您可以从模板中调用它,如下所示:
{{range .Pages}}{{end}}
本篇关于《使用 Go 模板在图像上应用随机整数》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

- 上一篇
- 隔离 label=username 的正则表达式

- 下一篇
- 使用Go Fiber构建HTTP服务器