Golang : Executing and evaluating nested loop in html template
Alright, just a minor problem and putting the solution here on how to fix this problem for future reference. Basically, I need to loop two slices inside HTML template and somehow the inner loop will not be evaluated. Attempts to range
over the inner slice will cause this error message:
template: editRenterPageBody:90:36: executing "editRenterPageBody" at <.currentlyRentedTheseProperties>: can't evaluate field currentlyRentedTheseProperties in type models.Property
and the code that caused this error message:
{{range $forRent := .propertiesForRent}} {{ range $rented := .currentlyRentedTheseProperties}} <!-- can't evaluate field error! --> <option value="{{ $forRent.ID }}" {{ if (eq $forRent.ID $rented.ID )}} {{ print "selected" }} {{ end }}>{{ (wordlimiter $forRent.Name 5) }}</option> {{end}} {{end}}
after some investigation, the error message is caused by a missing '$`. We can read from the official documentation:
When execution begins, $ is set to the data argument passed to Execute, that is, to the starting value of dot.
Therefore, to fix this problem, we just add a $
in front of the inner loop.
{{range $forRent := .propertiesForRent}} {{ range $rented := $.currentlyRentedTheseProperties}} <!-- need $. here instead of . --> <option value="{{ $forRent.ID }}" {{ if (eq $forRent.ID $rented.ID )}} {{ print "selected" }} {{ end }}>{{ (wordlimiter $forRent.Name 5) }}</option> {{end}} {{end}}
Hope this helps!
Happy coding!
Reference :
See also : Golang : How to use if, eq and print properly in html template
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+22.8k Golang : Daemonizing a simple web server process example
+4.7k Fix yum-complete-transaction error
+11.6k Golang : Drop cookie to visitor's browser and http.SetCookie() example
+9.7k Golang : Generate random elements without repetition or duplicate
+4.6k Golang : ROT32768 (rotate by 0x80) UTF-8 strings example
+24.6k Mac/Linux and Golang : Fix bind: address already in use error
+29.4k Golang : bufio.NewReader.ReadLine to read file line by line
+6.5k Golang : What fmt.Println() can do and println() cannot do
+5.6k Golang : Totalize or add-up an array or slice example
+3.8k Python : Find out the variable type and determine the type with simple test
+30.9k Golang : Convert []string to []byte examples
+21.2k Golang : Convert Unix timestamp to UTC timestamp