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 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试