首頁 > 後端開發 > Golang > 主體

如何使用Golang在HTML模板中計算?

Patricia Arquette
發布: 2024-11-14 21:08:02
原創
835 人瀏覽過

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:

  • [Golang templates (and passing funcs to template)](https://go.dev/play/p/7g4W1ypx2rB)
  • [How do I access object field by variable in template?](https://stackoverflow.com/questions/16910419/how-do-i-access-object-field-by-variable-in-template)
  • [Iterate Go map get index](https://stackoverflow.com/questions/19464257/iterate-go-map-get-index)

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

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板