Home > Backend Development > Golang > Using random Int for photos in Go template

Using random Int for photos in Go template

WBOY
Release: 2024-02-10 09:09:09
forward
937 people have browsed it

在 Go 模板中对照片使用随机 Int

php Editor Zimo In Go templates, we often need to process photos, and using random Int can help us achieve some interesting effects. Random Int is a function that generates random integers. We can use it to perform random operations on photos in templates, such as randomly displaying different photos, randomly adding filter effects to photos, etc. This article will detail how to use random Ints in Go templates to process photos, and give some examples of practical applications. Whether you are a beginner or an experienced developer, you can learn some practical tips about Go templates and random Ints from this article.

Question content

I have a simple random integer in my code that I pass to the 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,
            })
Copy after login

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

{{Range.Page}}

<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>
Copy after login

src="{{.photo}}" will crash the template as if the variable was not passed correctly. Maybe the problem is that this is within a loop, so I need a random number per post to display the photos?

Is there any other method that can be executed directly in the template?

renew

Thanks for the guidance I have now

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,   
            })
Copy after login

In template

{{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}}
Copy after login

Also tried

<a href="{{.slug}} ">    <img
        
 src="/public/suisse/suisse{{index $.photos $idx}}.jpg"
               alt=""
      /></a>
Copy after login

But unfortunately, the template stops executing once I call it

{{index $.Photos $idx}}
Copy after login

I think this is some kind of typo on my end?

Workaround

{{range}} The operation changes the points, so {{range .pages}} within {.photo}} will resolve to the element .pages.

Use

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

src="{{$.photo}}"
Copy after login

Although this is just an integer, you may want to use it in a path or url, like this:

src="/path/to/images?id={{$.photo}}"
Copy after login

Note: If you want to use different images for all pages, you must pass a different number for each page, not just a single number. Then add a

photo field to the page and then you can reference it in {{range}} like {{.photo}}## in the original code # . You wrote that you cannot modify

page

because it comes from your database. If so, pass a range of random numbers and access them using index like this: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false;">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, })</pre><div class="contentsignin">Copy after login</div></div> In template:

{{range $idx, $page := .pages}}
    <a href="{{.slug}} "><img
        src="{{index $.photos $idx}}"
        alt=""/>
    </a>
{{end}}
Copy after login

Or register a

random

function that you can call from the template: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false;">// 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;)</pre><div class="contentsignin">Copy after login</div></div> You can call it from a template like this:

{{range .Pages}}
    <a href="{{.Slug}} "><img
        src="{{random}}"
        alt=""/>
    </a>
{{end}}
Copy after login

The above is the detailed content of Using random Int for photos in Go template. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template