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:
以上是如何使用Golang在HTML模板中計算?的詳細內容。更多資訊請關注PHP中文網其他相關文章!