drsh30452 2017-07-29 13:25
浏览 581
已采纳

有没有一种有效的方法来连接golang模板中的字符串

For example, there is a function like that:

 func TestFunc(str string) string {
 return strings.Trim(str," ")
 }

It runs in the example below:

 {{ $var := printf "%s%s" "x" "y" }}
 {{ TestFunc $var }}

Is there anyway to concatenate strings with operators in template ?

 {{ $var := "y" }}
 {{ TestFunc "x" + $var }}

or

 {{ $var := "y" }}
 {{ TestFunc "x" + {$var} }}

It gives unexpected "+" in operand error.

I couldnt find it in documentation (https://golang.org/pkg/text/template/)

  • 写回答

1条回答 默认 最新

  • dongwen5870 2017-07-29 14:08
    关注

    There is not a way to concatenate strings with an operator because Go templates do not have operators.

    Use the printf function as shown in the question or combine the calls in a single template expression:

    {{ TestFunc (printf "%s%s" "x" "y") }}
    

    If you always need to concatenate strings for the TestFunc argument, then write TestFunc to handle the concatenation:

    func TestFunc(strs ...string) string {
       return strings.Trim(strings.Join(strs, ""), " ")
    }
    
    {{ TestFunc "x"  $var }}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 win2012 iscsi ipsec
  • ¥15 封装的 matplotlib animation 不显示图像
  • ¥15 python摄像头画面无法显示
  • ¥15 关于#3d#的问题:d标定算法(语言-python)
  • ¥15 cve,cnnvd漏洞扫描工具推荐
  • ¥15 图像超分real-esrgan网络自己训练模型遇到问题
  • ¥15 如何构建全国统一的物流管理平台?
  • ¥100 ijkplayer使用AndroidStudio/CMake编译,如何支持 rtsp 直播流?
  • ¥15 用js遍历数据并对非空元素添加css样式
  • ¥15 使用autodl云训练,希望有直接运行的代码(关键词-数据集)