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

如何在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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 zynq7015,PCIE读写延时偏大
  • ¥15 使用spss做psm(倾向性评分匹配)遇到问题
  • ¥20 vue+UEditor附件上传问题
  • ¥15 想做个WPS的自动化代码,不知道能做的起不。
  • ¥15 uniApp,生成安卓安卓包后,黑暗主题中间内容不生效,底部导航正常
  • ¥15 斯坦福自动漂移非线性模型反解
  • ¥15 学习Python如何找兼职
  • ¥15 python结合Matlab仿真忆阻器
  • ¥35 有人会注册whatsaop协议号吗?
  • ¥15 lead dbs 无法导入影像数据