当映射查找失败时,从模板返回解析错误。

huangapple go评论88阅读模式
英文:

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

 &lt;h1&gt; You sent in {{.Field1}} and {{.Field2}} &lt;/h1&gt; 

The payload will be: {&quot;Field1&quot;: &quot;Value1&quot;, &quot;Field2&quot;: &quot;Value2&quot;}

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>`))

playground example

英文:

Using the "missingkey=error" option.

tmpl := template.Must(template.New(&quot;&quot;).Option(&quot;missingkey=error&quot;).Parse(
      `&lt;h1&gt; You sent in {{.Field1}} and {{.Field2}} &lt;/h1&gt;`))

playground example

huangapple
  • 本文由 发表于 2016年4月1日 00:45:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/36339219.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定