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

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

Use Random Int for a Photo in Go Template

问题

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

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,
})

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

{{range .Pages}}
    <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>
            ...
          </div>
        </p>
      </div>
    </div>
{{end}}

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}}
    <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>
        </p>
      </div>
    </div>
{{end}}

我还尝试了以下代码:

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

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

英文:

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

            min := 1
			max := 1563
			Photo := rand.Intn(max - min + 1)
			fmt.Println(Photo)

			tmpl.ExecuteTemplate(w, &quot;index.html&quot;, 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 &lt; totalPaginationPage,
				ShowPrevious: pageIndex-1 &gt;= 0,
				Photo:        Photo,
			})

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

{{range .Pages}}

&lt;div id=&quot;content&quot;&gt;
  &lt;div class=&quot;card&quot;&gt;
    &lt;p&gt;
      &lt;div class=&quot;card-img&quot;&gt;

  
    
        &lt;a href=&quot;{{.Slug}} &quot;&gt;    &lt;img
        

        src=&quot;{{.Photo}}&quot;
        alt=&quot;&quot;
      /&gt;&lt;/a&gt;
        &lt;/div&gt;
        
        &lt;div class=&quot;card-info&quot;&gt;
          &lt;div class=&quot;card-info-title&quot;&gt;
&lt;a href=&quot;{{.Slug}} &quot; &gt;{{.Title}} &lt;/a&gt;
&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

min := 1
max := 1563
Photos := make([]int, len(pages))
for i := range Photos {
    Photos[i] = rand.Intn(max - min + 1)
}
			

			tmpl.ExecuteTemplate(w, &quot;index.html&quot;, 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 &lt; totalPaginationPage,
				ShowPrevious: pageIndex-1 &gt;= 0,
				Photo:        Photos,	
			})

and in the template

{{range $idx, $page := .Pages}}


&lt;div id=&quot;content&quot;&gt;
  &lt;div class=&quot;card&quot;&gt;
    &lt;p&gt;
      &lt;div class=&quot;card-img&quot;&gt;

  
    
        &lt;a href=&quot;{{.Slug}} &quot;&gt;    &lt;img
        
 src=&quot;{{index $.Photos $idx}}&quot;
               alt=&quot;&quot;
      /&gt;&lt;/a&gt;
        &lt;/div&gt;
        
        &lt;div class=&quot;card-info&quot;&gt;
          &lt;div class=&quot;card-info-title&quot;&gt;
&lt;a href=&quot;{{.Slug}} &quot; &gt;{{.Title}} &lt;/a&gt;
&lt;/div&gt;

&lt;div class=&quot;card-info-category&quot;&gt;
  &lt;p&gt;

tags:
&lt;/p&gt;
       
          &lt;ul&gt;
       
            &lt;li&gt;
  {{.Tags}}
          &lt;/li&gt;
  

&lt;/ul&gt;
&lt;/div&gt;


&lt;div class=&quot;card-info-date&quot;&gt;
{{.Date}} 

&lt;/div&gt;

&lt;/div&gt;
&lt;/p&gt;
&lt;/div&gt;

&lt;/div&gt;



       
{{end}} 

also tried

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

but unfortunately the templates stop executing as soon as I call

{{index $.Photos $idx}} 

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

答案1

得分: 1

{{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}}
    <a href="{{.Slug}}"><img
        src="{{index $.Photos $idx}}"
        alt=""/>
    </a>
{{end}}

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

// 像之前一样解析模板,但是首先注册一个random函数:
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}}
    <a href="{{.Slug}}"><img
        src="{{random}}"
        alt=""/>
    </a>
{{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:

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:

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:

min := 1
max := 1563
Photos := make([]int, len(pages))
for i := range Photos {
    Photos[i] = rand.Intn(max - min + 1)
}

tmpl.ExecuteTemplate(w, &quot;index.html&quot;, 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 &lt; totalPaginationPage,
    ShowPrevious: pageIndex-1 &gt;= 0,
    Photo:        Photos,
})

In template:

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

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

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

And you can call it from the template like this:

{{range .Pages}}
    &lt;a href=&quot;{{.Slug}} &quot;&gt;&lt;img
        src=&quot;{{random}}&quot;
        alt=&quot;&quot;/&gt;
    &lt;/a&gt;
{{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:

确定