英文:
Returning parse error from templates when map lookup fails
问题
我有一系列使用通用的map[string]string
值的模板。类似于:
<h1> You sent in {{.Field1}} and {{.Field2}} </h1>
负载将是:{"Field1": "Value1", "Field2": "Value2"}
调用方式为:err := tmpl.Execute(w, data); // data是map[string]string类型,并且从负载中解码而来
我无法将data
转换为struct
,因为模板和负载是在运行时确定的。这些模板是由业务用户创建的,我不想为每个模板创建一个类型,并在每次有新模板时更改后端。因此,希望保持map[string]string
的解决方案。
上述设计的问题是,当模板中使用的字段在运行时未传递时,执行模板时缺少的字段会在模板中返回空字符串。如果发生这种情况,我希望返回一个错误。
所以,我想知道是否有一种方法可以使模板在映射查找失败时返回解析错误?或者是否有一种方法可以将带有运行时错误检查的通用struct
值传递给允许动态负载的模板?
谢谢!
英文:
I have a series of templates that use generic map[string]string
value in them. Something like
<h1> You sent in {{.Field1}} and {{.Field2}} </h1>
The payload will be: {"Field1": "Value1", "Field2": "Value2"}
Called as: err := tmpl.Execute(w, data); // data is map[string]string and was decoded from the payload
I cannot convert data
to a struct
as the templates and payload are determined at runtime. These templates are created by business users and I don't want to create a type for each template and change the backend every time there is a new template. Hence the desire to keep the map[string]string
like solution.
The issue with the above design is that when a field used in the template is not passed in at runtime. When I execute the template, the missing fields return an empty string in the template. I would like to return an error if that happens.
So, I would like to know if there a way to make the template return a parse error when the map-lookup fails? Or is there a way to pass generic struct
values with runtime error checking to a template that allows for dynamic payloads?
Thanks!
答案1
得分: 3
使用"missingkey=error"选项。
tmpl := template.Must(template.New("").Option("missingkey=error").Parse(
`<h1> You sent in {{.Field1}} and {{.Field2}} </h1>`))
英文:
Using the "missingkey=error" option.
tmpl := template.Must(template.New("").Option("missingkey=error").Parse(
`<h1> You sent in {{.Field1}} and {{.Field2}} </h1>`))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论