如果对象为nil,则在模板中显示默认内容,否则根据set属性显示 [英] Show default content in a template if an object is nil otherwise show based on the set property

查看:32
本文介绍了如果对象为nil,则在模板中显示默认内容,否则根据set属性显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的模板中,我想包含一些默认的 meta 标记(90%的时间).但是,设置了特定属性后,我想显示另一组文本.

In my template, I would like to include some default meta tags (90% of the time). However, when a specific property is set, I would like to show a different set of text.

我知道我可以设置一个匿名 struct 并使用"default" "some-x" 设置属性.但是,这意味着,我需要向当前仅通过 nil 传递的90%的处理程序中添加一个匿名结构.

I know I can set an anonymous struct and set a property with either "default" or "some-x". However, this means, I need to add an anonymous struct to 90% of my handlers that just currently pass nil.

有没有办法做类似的事情

Is there way to do something like

{{if eq . nil}} 
   // default meta tag
{{else if eq .MetaValue "some-x"}} 
   //other
{{end}}

如果我尝试类似上面的代码,它将编译但不能执行我想要的操作.赞赏有关如何正确处理它的建议,而无需增加很多样板.

If I try something like my above code, it compiles but doesn't do what I want. Appreciate any suggestions on how to handle it properly without adding a lot of boiler plate.

谢谢!

推荐答案

{{if not .}}
   output when . is nil or otherwise empty including
     false, 0, and any array, slice, map, or string of length zero
{{else if eq .MetaValue "some-x"}}
       // some-x case
{{else}} 
       // other case
{{end}}

这篇关于如果对象为nil,则在模板中显示默认内容,否则根据set属性显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆