DEV Community

loading...

Need helping looping over Go struct/array in .html file

ohhnate profile image Samuel Fuller ・2 min read

Hello, this is my first post and I am also a web development noob. I apologize if this issue is basic.

I have a main.go file which contains a struct that contains an array. I would like to display all of the contents of the array within a separate .html file. I have managed to get it working without looping but I would like to display the entire array as the size and contents change. I will show the different iterations I have tried at the bottom.

Current working hard coded array contents

    <h1>{{(index .Results 0).Title}}</h1>
    <h1>{{(index .Results 0).ReleaseDate}}</h1>
    <img src="https://image.tmdb.org/t/p/w500/{{(index .Results 0).PosterPath}}">
    <h1>{{(index .Results 1).Title}}</h1>
    <h1>{{(index .Results 1).ReleaseDate}}</h1>
    <img src="https://image.tmdb.org/t/p/w500/{{(index .Results 1).PosterPath}}">
    <h1>{{(index .Results 2).Title}}</h1>
    <h1>{{(index .Results 2).ReleaseDate}}</h1>
    <img src="https://image.tmdb.org/t/p/w500/{{(index .Results 2).PosterPath}}">

Struct in main.go file. Trying to access Results[]

type Movies struct {
    TotalResults int `json:"total_results"`
    Results      []struct {
        PosterPath   string `json:"poster_path"`
        ID           int    `json:"id"`
        Title        string `json:"title"`
        Overview     string `json:"overview"`
        ReleaseDate  string `json:"release_date"`
    } `json:"results"`
}

Adding this for clarity.(no issues here) main.go function that handles the searching. GET request from movieDB API.

func search(w http.ResponseWriter, r *http.Request) {
    var movies Movies
    if r.Method != "POST" {
        http.Redirect(w, r, "/", http.StatusSeeOther)
        return
    }
    searchValue := r.FormValue("query")
    //replace spaces with addition signs
    searchResult := strings.Replace(searchValue, " ", "+", -1)

    response, err := http.Get("https://api.themoviedb.org/3/search/movie?api_key=xxxREDACTEDxxx&query=" + searchResult)
    if err != nil {
        fmt.Printf("The HTTP request failed with error %s\n", err)
    } else {
        data, _ := ioutil.ReadAll(response.Body)
        json.Unmarshal([]byte(data), &movies)
    }
    tpl.ExecuteTemplate(w, "search.html", movies)
}

Loop I've tried that doesn't compile because 'i' isn't recognized

<script>
      for (var i in {{.Results}}) {
        document.body.innerHTML = "<h1>" + {{.Results[i].Title}} + "</h1>"
      }
</script>

This loop compiles but displays nothing

<script>
      for (var i in {{.Results}}) {
        document.body.innerHTML = "<h1>" + .Results[i].Title + "</h1>"
      }
</script>

This loop displays 'undefined'

<script>
    var arr = {{.Results}}
      for (var i in arr) {
        document.body.innerHTML = "<h1>" + arr[i].Title + "</h1>"
      }
</script>

I am currently out of ideas and I am just having a hard time wrapping my head around getting the information from one place to another(and javascript in general). Any help would greatly be appreciated thank you.

Discussion (3)

pic
Editor guide
Collapse
javapriyan profile image
Karthikeyan • Edited

I am not sure why do you need this to be in the script tag. Iterate the h1 as usual with the template. It does the magic

Collapse
ohhnate profile image
Samuel Fuller Author

Ahhhhhh I see what you mean. I've been thinking about templates all wrong. I'm pretty sure I can get it fixed now. Thank you for the advice.

Collapse
javapriyan profile image
Karthikeyan

I am glad that helped. Happy hacking