问题描述
您如何计算go的html模板中的内容?
How can you calculate something inside a html template of go?
例如:
{{ $length := len . }}
<p>The last index of this map is: {{ $length -1 }} </p>
是.
是地图.
代码 {{$ length -1}}
无法正常工作,有没有办法实现?
Were the .
is a map.
The code {{ $length -1 }}
is not working, is there a way to achieve this?
推荐答案
您不能.模板不是脚本语言.按照设计哲学,复杂的逻辑应该在模板之外.
You can't. Templates are not a scripting language. By design philosophy, complex logic should be outside of templates.
要么将计算结果作为参数传递(首选/最简单),要么注册可在模板执行期间调用的自定义函数,将值传递给它们,并可以执行计算并返回任何值(例如,返回 param-1
).
Either pass the calculated result as a parameter (preferred / easiest), or register custom functions which you can call during template execution, pass values to them and which may perform calculations and return any values (e.g. return param - 1
).
有关注册和使用自定义功能的示例,请参见:
For examples of registering and using custom functions, see:
这篇关于如何计算html/template中的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!