带有 Go html 模板的动态字段

问题描述

我可以在 go 中使用动态属性制作 html 模板吗?

像这样当前导致错误

无效模板:模板:sticker.CellRepresentation:1:23:在<.sticker_set.url>处执行“sticker.CellRepresentation”:无法在类型接口{}

中评估字段url
$prd = Product::where($args)->whereBetween('price',[(int)($request->min_price),(int)($request->max_price)])->get();

我没有使用结构体,因为我尝试执行的模板使用的是未在编译时定义的结构体的 json

解决方法

你的例子对我和在操场上都很好。我稍微调整了模板并使用 os.stdout 作为作者。

func sample() error {
    tpl,err := template.New("sample").Parse(`<a href="{{.sticker_set.url}}">{{.sticker_set.url}}</a>`)
    if err != nil {
        return err
    }

    data := map[string]interface{}{
        "sticker_set": map[string]interface{}{
            "url": "xyz",},}

    if err := tpl.Execute(os.Stdout,data); err != nil {
        return fmt.Errorf("Invalid template: %w",err)
    }

    return nil
}

甚至尝试使用不同的值类型:Playground