我的代码中有一个简单的随机整数,我将其传递给模板
min := 1
max := 1563
Photo := rand.Intn(max - min + 1)
fmt.Println(Photo)
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: Photo,
})
我的 idea 是随机化一张照片(我在文件夹中有1563张),所以在我的模板中
{范围.页面}
<div id="content">
<div class="card">
<p>
<div class="card-img">
<a href="{{.Slug}} "> <img
src="{{.Photo}}"
alt=""
/></a>
</div>
<div class="card-info">
<div class="card-info-title">
<a href="{{.Slug}} " >{{.Title}} </a>
</div>
SRC="{{.Photo}}"使模板崩溃,就像没有正确传递变量一样.也许问题是这是在一个循环中,所以我需要每个文章一个随机数字才能显示照片?
有没有其他方法可以直接在模板中完成?
Update个
多亏了我现在的指导
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}}
<div id="content">
<div class="card">
<p>
<div class="card-img">
<a href="{{.Slug}} "> <img
src="{{index $.Photos $idx}}"
alt=""
/></a>
</div>
<div class="card-info">
<div class="card-info-title">
<a href="{{.Slug}} " >{{.Title}} </a>
</div>
<div class="card-info-category">
<p>
tags:
</p>
<ul>
<li>
{{.Tags}}
</li>
</ul>
</div>
<div class="card-info-date">
{{.Date}}
</div>
</div>
</p>
</div>
</div>
{{end}}
也试过了
<a href="{{.Slug}} "> <img
src="/public/suisse/suisse{{index $.Photos $idx}}.jpg"
alt=""
/></a>
但不幸的是,只要我调用,模板就会停止执行
{{index $.Photos $idx}}
我想这是我这边的某种打字错误吧?