Home >Backend Development >Golang >How to Perform Calculations in HTML Templates with Golang?
Calculating Values in HTML Templates with Golang
How do you perform calculations within HTML templates in Go? Consider this example:
{{ $length := len . }} <p>The last index of this map is: {{ $length -1 }} </p>
where . represents a map. While the code {{ $length -1 }} seems logical, it doesn't work. Is there a solution?
Solution
Templates in Go are not designed for scripting language capabilities. Complex logic should be handled outside of templates.
To achieve the desired result, you can either pass the calculated result as a parameter or register custom functions that can be invoked during template execution. These functions can perform calculations, pass values, and return outcomes.
Custom Functions
Below are references to demonstrations of registering and using custom functions:
The above is the detailed content of How to Perform Calculations in HTML Templates with Golang?. For more information, please follow other related articles on the PHP Chinese website!