在Go模板中使用Random Int来生成一个随机数。

huangapple go评论111阅读模式
英文:

Use Random Int for a Photo in Go Template

问题

我在代码中有一个简单的随机整数,我将其传递给模板。

  1. min := 1
  2. max := 1563
  3. Photo := rand.Intn(max - min + 1)
  4. fmt.Println(Photo)
  5. tmpl.ExecuteTemplate(w, "index.html", struct {
  6. Pages []Page
  7. CurrentPage int
  8. TotalPage int
  9. NextPage int
  10. PreviousPage int
  11. LastPage int
  12. ShowNext bool
  13. ShowPrevious bool
  14. Photo int
  15. }{
  16. Pages: pages,
  17. CurrentPage: pageIndex + 1,
  18. TotalPage: totalPaginationPage,
  19. NextPage: pageIndex + 1,
  20. PreviousPage: pageIndex - 1,
  21. LastPage: totalPaginationPage - 1,
  22. ShowNext: pageIndex+1 < totalPaginationPage,
  23. ShowPrevious: pageIndex-1 >= 0,
  24. Photo: Photo,
  25. })

我的想法是随机选择一张照片(文件夹中有1563张),然后在模板中使用。

  1. {{range .Pages}}
  2. <div id="content">
  3. <div class="card">
  4. <p>
  5. <div class="card-img">
  6. <a href="{{.Slug}}">
  7. <img src="{{.Photo}}" alt=""/>
  8. </a>
  9. </div>
  10. <div class="card-info">
  11. <div class="card-info-title">
  12. <a href="{{.Slug}}">{{.Title}}</a>
  13. </div>
  14. ...
  15. </div>
  16. </p>
  17. </div>
  18. </div>
  19. {{end}}

src="{{.Photo}}" 导致模板崩溃,好像变量没有正确传递。也许问题在于这是在循环内部,所以我需要为每篇文章生成一个随机数以显示一张照片?

有没有其他方法可以直接在模板中完成?

更新

根据指导,我现在有以下代码:

  1. min := 1
  2. max := 1563
  3. Photos := make([]int, len(pages))
  4. for i := range Photos {
  5. Photos[i] = rand.Intn(max - min + 1)
  6. }
  7. tmpl.ExecuteTemplate(w, "index.html", struct {
  8. Pages []Page
  9. CurrentPage int
  10. TotalPage int
  11. NextPage int
  12. PreviousPage int
  13. LastPage int
  14. ShowNext bool
  15. ShowPrevious bool
  16. Photo []int
  17. }{
  18. Pages: pages,
  19. CurrentPage: pageIndex + 1,
  20. TotalPage: totalPaginationPage,
  21. NextPage: pageIndex + 1,
  22. PreviousPage: pageIndex - 1,
  23. LastPage: totalPaginationPage - 1,
  24. ShowNext: pageIndex+1 < totalPaginationPage,
  25. ShowPrevious: pageIndex-1 >= 0,
  26. Photo: Photos,
  27. })

在模板中:

  1. {{range $idx, $page := .Pages}}
  2. <div id="content">
  3. <div class="card">
  4. <p>
  5. <div class="card-img">
  6. <a href="{{.Slug}}">
  7. <img src="{{index $.Photos $idx}}" alt=""/>
  8. </a>
  9. </div>
  10. <div class="card-info">
  11. <div class="card-info-title">
  12. <a href="{{.Slug}}">{{.Title}}</a>
  13. </div>
  14. ...
  15. </div>
  16. </p>
  17. </div>
  18. </div>
  19. {{end}}

我还尝试了以下代码:

  1. <a href="{{.Slug}}">
  2. <img src="/public/suisse/suisse{{index $.Photos $idx}}.jpg" alt=""/>
  3. </a>

但不幸的是,模板在调用 {{index $.Photos $idx}} 后停止执行。我猜这可能是我这边的一个拼写错误?

英文:

I have a simple random integer in my code that I am passing to the template

  1. min := 1
  2. max := 1563
  3. Photo := rand.Intn(max - min + 1)
  4. fmt.Println(Photo)
  5. tmpl.ExecuteTemplate(w, &quot;index.html&quot;, struct {
  6. Pages []Page
  7. CurrentPage int
  8. TotalPage int
  9. NextPage int
  10. PreviousPage int
  11. LastPage int
  12. ShowNext bool
  13. ShowPrevious bool
  14. Photo int
  15. }{
  16. Pages: pages,
  17. CurrentPage: pageIndex + 1,
  18. TotalPage: totalPaginationPage,
  19. NextPage: pageIndex + 1,
  20. PreviousPage: pageIndex - 1,
  21. LastPage: totalPaginationPage - 1,
  22. ShowNext: pageIndex+1 &lt; totalPaginationPage,
  23. ShowPrevious: pageIndex-1 &gt;= 0,
  24. Photo: Photo,
  25. })

the idea is to randomize a photo (I have 1563 in the folder) so in my template

{{range .Pages}}

  1. &lt;div id=&quot;content&quot;&gt;
  2. &lt;div class=&quot;card&quot;&gt;
  3. &lt;p&gt;
  4. &lt;div class=&quot;card-img&quot;&gt;
  5. &lt;a href=&quot;{{.Slug}} &quot;&gt; &lt;img
  6. src=&quot;{{.Photo}}&quot;
  7. alt=&quot;&quot;
  8. /&gt;&lt;/a&gt;
  9. &lt;/div&gt;
  10. &lt;div class=&quot;card-info&quot;&gt;
  11. &lt;div class=&quot;card-info-title&quot;&gt;
  12. &lt;a href=&quot;{{.Slug}} &quot; &gt;{{.Title}} &lt;/a&gt;
  13. &lt;/div&gt;

src="{{.Photo}}" crashes the template, is like if the variable is not properly passed. Perhaps the issue is that this is inside a loop so I need a random number per each article in order to display a photo ?

Is there any other way to do it directly in the template ?

Update

Thanks to the guidance I now have

  1. min := 1
  2. max := 1563
  3. Photos := make([]int, len(pages))
  4. for i := range Photos {
  5. Photos[i] = rand.Intn(max - min + 1)
  6. }
  7. tmpl.ExecuteTemplate(w, &quot;index.html&quot;, struct {
  8. Pages []Page
  9. CurrentPage int
  10. TotalPage int
  11. NextPage int
  12. PreviousPage int
  13. LastPage int
  14. ShowNext bool
  15. ShowPrevious bool
  16. Photo []int
  17. }{
  18. Pages: pages,
  19. CurrentPage: pageIndex + 1,
  20. TotalPage: totalPaginationPage,
  21. NextPage: pageIndex + 1,
  22. PreviousPage: pageIndex - 1,
  23. LastPage: totalPaginationPage - 1,
  24. ShowNext: pageIndex+1 &lt; totalPaginationPage,
  25. ShowPrevious: pageIndex-1 &gt;= 0,
  26. Photo: Photos,
  27. })

and in the template

  1. {{range $idx, $page := .Pages}}
  2. &lt;div id=&quot;content&quot;&gt;
  3. &lt;div class=&quot;card&quot;&gt;
  4. &lt;p&gt;
  5. &lt;div class=&quot;card-img&quot;&gt;
  6. &lt;a href=&quot;{{.Slug}} &quot;&gt; &lt;img
  7. src=&quot;{{index $.Photos $idx}}&quot;
  8. alt=&quot;&quot;
  9. /&gt;&lt;/a&gt;
  10. &lt;/div&gt;
  11. &lt;div class=&quot;card-info&quot;&gt;
  12. &lt;div class=&quot;card-info-title&quot;&gt;
  13. &lt;a href=&quot;{{.Slug}} &quot; &gt;{{.Title}} &lt;/a&gt;
  14. &lt;/div&gt;
  15. &lt;div class=&quot;card-info-category&quot;&gt;
  16. &lt;p&gt;
  17. tags:
  18. &lt;/p&gt;
  19. &lt;ul&gt;
  20. &lt;li&gt;
  21. {{.Tags}}
  22. &lt;/li&gt;
  23. &lt;/ul&gt;
  24. &lt;/div&gt;
  25. &lt;div class=&quot;card-info-date&quot;&gt;
  26. {{.Date}}
  27. &lt;/div&gt;
  28. &lt;/div&gt;
  29. &lt;/p&gt;
  30. &lt;/div&gt;
  31. &lt;/div&gt;
  32. {{end}}

also tried

  1. &lt;a href=&quot;{{.Slug}} &quot;&gt; &lt;img
  2. src=&quot;/public/suisse/suisse{{index $.Photos $idx}}.jpg&quot;
  3. alt=&quot;&quot;
  4. /&gt;&lt;/a&gt;

but unfortunately the templates stop executing as soon as I call

  1. {{index $.Photos $idx}}

I assume it is a typo of some sort from my side?

答案1

得分: 1

{{range}}操作会改变点(.),所以在{{range .Pages}}内部的{{.Photo}}将会解析为.Pages中的元素。

使用$来引用模板执行时传递的“外部”原始值:

  1. src="{{$.Photo}}"

尽管这只是一个整数,但你可能想在路径或URL中使用它,类似于这样:

  1. src="/path/to/images?id={{$.Photo}}"

注意:如果你想为所有页面使用不同的图片,你需要为每个页面传递一个不同的数字,而不仅仅是一个。然后在页面中添加一个Photo字段,然后你可以在{{range}}内部使用{{.Photo}},就像你原来的代码中那样。

你写道你不能修改Page,因为它来自你的数据库。如果是这样,那么可以传递一个随机数的切片,并使用index来访问它们,就像这样:

  1. min := 1
  2. max := 1563
  3. Photos := make([]int, len(pages))
  4. for i := range Photos {
  5. Photos[i] = rand.Intn(max - min + 1)
  6. }
  7. tmpl.ExecuteTemplate(w, "index.html", struct {
  8. Pages []Page
  9. CurrentPage int
  10. TotalPage int
  11. NextPage int
  12. PreviousPage int
  13. LastPage int
  14. ShowNext bool
  15. ShowPrevious bool
  16. Photo []int
  17. }{
  18. Pages: pages,
  19. CurrentPage: pageIndex + 1,
  20. TotalPage: totalPaginationPage,
  21. NextPage: pageIndex + 1,
  22. PreviousPage: pageIndex - 1,
  23. LastPage: totalPaginationPage - 1,
  24. ShowNext: pageIndex+1 < totalPaginationPage,
  25. ShowPrevious: pageIndex-1 >= 0,
  26. Photo: Photos,
  27. })

在模板中:

  1. {{range $idx, $page := .Pages}}
  2. <a href="{{.Slug}}"><img
  3. src="{{index $.Photos $idx}}"
  4. alt=""/>
  5. </a>
  6. {{end}}

或者注册一个random函数,你可以在模板中调用它:

  1. // 像之前一样解析模板,但是首先注册一个random函数:
  2. min, max := 1, 1563
  3. tmpl, err := template.New("").Funcs(template.FuncMap{
  4. "random": func() int { return rand.Intn(max - min + 1) },
  5. }).ParseFiles("template-name.html")

然后你可以在模板中这样调用它:

  1. {{range .Pages}}
  2. <a href="{{.Slug}}"><img
  3. src="{{random}}"
  4. alt=""/>
  5. </a>
  6. {{end}}
英文:

The {{range}} action changes the dot, so {{.Photo}} inside the {{range .Pages}} will be resolved on the elements of .Pages.

Use $ to refer to the "outer", original value passed to the template execution:

  1. src=&quot;{{$.Photo}}&quot;

Although this is only an integer, you likely want to use it in a path or an URL, something like this:

  1. src=&quot;/path/to/images?id={{$.Photo}}&quot;

Note: If you want a different image for all pages, you have to pass a different number for each, not just a single one. Then add a Photo field to page, and then you can refer to it inside the {{range}} as {{.Photo}} as in your original code.

You wrote you can't modify Page as it comes from your database. If so, then either pass a slice of random numbers and access them with index like this:

  1. min := 1
  2. max := 1563
  3. Photos := make([]int, len(pages))
  4. for i := range Photos {
  5. Photos[i] = rand.Intn(max - min + 1)
  6. }
  7. tmpl.ExecuteTemplate(w, &quot;index.html&quot;, struct {
  8. Pages []Page
  9. CurrentPage int
  10. TotalPage int
  11. NextPage int
  12. PreviousPage int
  13. LastPage int
  14. ShowNext bool
  15. ShowPrevious bool
  16. Photo []int
  17. }{
  18. Pages: pages,
  19. CurrentPage: pageIndex + 1,
  20. TotalPage: totalPaginationPage,
  21. NextPage: pageIndex + 1,
  22. PreviousPage: pageIndex - 1,
  23. LastPage: totalPaginationPage - 1,
  24. ShowNext: pageIndex+1 &lt; totalPaginationPage,
  25. ShowPrevious: pageIndex-1 &gt;= 0,
  26. Photo: Photos,
  27. })

In template:

  1. {{range $idx, $page := .Pages}}
  2. &lt;a href=&quot;{{.Slug}} &quot;&gt;&lt;img
  3. src=&quot;{{index $.Photos $idx}}&quot;
  4. alt=&quot;&quot;/&gt;
  5. &lt;/a&gt;
  6. {{end}}

Or register a random function which you can call from the template:

  1. // Parse the template as you did, but first register a random function:
  2. min, max := 1, 1563
  3. tmpl, err := template.New(&quot;&quot;).Funcs(template.FuncMap{
  4. &quot;random&quot;: func() int { return rand.Intn(max - min + 1) },
  5. }).ParseFiles(&quot;template-name.html&quot;)

And you can call it from the template like this:

  1. {{range .Pages}}
  2. &lt;a href=&quot;{{.Slug}} &quot;&gt;&lt;img
  3. src=&quot;{{random}}&quot;
  4. alt=&quot;&quot;/&gt;
  5. &lt;/a&gt;
  6. {{end}}

huangapple
  • 本文由 发表于 2022年11月28日 02:38:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/74592772.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定