donqh00404
2017-02-24 09:04
浏览 546
已采纳

如何在golang模板中检查字符串的空值

I have this below golang template code snippet where I take values from a map of type map[string]interface{} and check if that string is empty or not but my string empty check is failing as: template: apps.html:62:29: executing "apps.html" at <eq $src "">: error calling eq: invalid type for comparison . I tried to print the empty value also and it is rendered as <nil> but my {{if eq $src "<nil>"}} check is also failing and even if I put nil then also it fails. Is there any better way to achieve this.

    {{$src := (index . "source")}}
    {{$tar := (index . "target")}}
    {{if eq $src ""}}
          <div></div>
    {{else}}
          <div style="display:none;">
              <input id="username" name="source" value="{{ $src }}"/>
              <input id="username" name="target" value="{{ $tar }}"/>
          </div>
    {{end}}
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

  • duanlu8613 2017-02-24 09:41
    最佳回答

    Here is what you're doing (always better to give an example play.golang.org link if possible):

    https://play.golang.org/p/uisbAr_3Qy

    A few problems with what you're doing: If you're using a map for context, you don't need to use index at all, so your variables are not required. If you want to check if a key exists, just check for a nil entry with if. If your map contains elements of type interface, you can't compare with a string, only use eq when you're sure you have an element but are not sure what it might be, and wrap it in an if test if unsure whether the key exists.

    I think you want to do something like this:

    {{if .source }}
      <div style="display:none;">
        <input id="username" name="source" value="{{ .source }}"/>
        <input id="username" name="target" value="{{ .target }}"/>
      </div>
    {{else}}
      <div>empty</div>
    {{end}}
    

    https://play.golang.org/p/D2DCjAklFE

    See the docs for text/template as they have a lot more detail:

    https://golang.org/pkg/text/template/#hdr-Actions

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题