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
+34.4k Golang : Create x509 certificate, private and public keys
+9.8k Golang : How to extract video or image files from html source code
+6.4k Golang : Extract sub-strings
+9.8k PHP : Get coordinates latitude/longitude from string
+17.9k Golang : [json: cannot unmarshal object into Go value of type]
+9.5k Golang : Launch Mac OS X Preview (or other OS) application from your program example
+18.7k Golang : Logging with logrus
+12.5k Golang : List running EC2 instances and descriptions
+11.5k Golang : Characters limiter example
+5k Which content-type(MIME type) to use for JSON data
+22.1k Golang : Upload big file (larger than 100MB) to AWS S3 with multipart upload
+17.2k Golang : Covert map/slice/array to JSON or XML format