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

有没有一种有效的方法来连接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/)

图片转代码服务由CSDN问答提供 功能建议

例如,有一个类似的函数:

   func TestFunc(str字符串)字符串{
返回字符串。Trim(str,“”)
} 
   
 
 

它在以下示例中运行:

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

是否可以在模板中使用运算符将​​字符串连接起来?

  {{$ var:=“ y”}} 
 {{TestFunc“  x“ + $ var}} 
   
 
 

  {{$ var:=” y“}}  
 {{TestFunc“ x” + {$ var}}} 
   
 
 

它在操作数错误中给出了意外的“ +”。

我在文档中找不到它( 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 }}
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题