登录
首页 >  Golang >  Go问答

如何计算 html/template 中的内容

来源:stackoverflow

时间:2024-04-15 12:06:39 195浏览 收藏

来到golang学习网的大家,相信都是编程学习爱好者,希望在这里学习Golang相关编程知识。下面本篇文章就来带大家聊聊《如何计算 html/template 中的内容》,介绍一下,希望对大家的知识积累有所帮助,助力实战开发!

问题内容

如何计算 go 的 html 模板中的内容?

例如:

{{ $length := len . }}

The last index of this map is: {{ $length -1 }}

. 是一张地图吗?

代码 {{ $length -1 }} 不起作用,有办法实现吗?


解决方案


你不能。模板不是脚本语言。根据设计理念,复杂的逻辑应该在模板之外。

将计算结果作为参数传递(首选/最简单),或者注册可以在模板执行期间调用的自定义函数,将值传递给它们,并且可以执行计算并返回任何值(例如返回 param - 1)。

有关注册和使用自定义函数的示例,请参阅:

Golang templates (and passing funcs to template)

How do I access object field by variable in template?

Iterate Go map get index

其他答案是正确的,您不能在模板本身中执行此操作。不过,这里有一个如何使用 funcs 的工作示例:

package main

import (
    "fmt"
    "html/template"
    "os"
)

type MyMap map[string]string

func LastMapIndex(args ...interface{}) string {
    if m, ok := args[0].(MyMap); ok && len(args) == 1 {
        return fmt.Sprintf("%d", len(m) - 1)
    }
    return ""

}

func main() {
    myMap := MyMap{}
    myMap["foo"] = "bar"

    t := template.New("template test")
    t = t.Funcs(template.FuncMap{"LastMapIndex": LastMapIndex})
    t = template.Must(t.Parse("Last map index: {{.|LastMapIndex}}\n"))
    t.Execute(os.Stdout, myMap)
}

演示:https://play.golang.org/p/YNchaHc5Spz

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>