dqk94069 2014-08-06 15:28
浏览 240
已采纳

如何在模板中处理字符串格式

I pass a struct to a template that sometimes contain strings that are a tad too long for display. In any other language, I would've just attached a formatting rule in the template itself. What's the idiomatic approach to accomplish formatting in templates?

Example:

type struct MyStruct{
    something    string
    anotherThing string
}

In the template

<table>
{{ range .Rows }}      //NOTE! Rows is an array of MyStruct objects 
<tr>
<td>{{ .something }}</td>
<td>{{ .anotherThing }}</td>        
</tr>
{{ end }}
</table>

In case it isn't obvious from the above, the question is "How would you go about making sure .anotherThing or .something doesn't display more than say 40 characters?

One solution COULD be to make the struct contain four values, the two raw strings and two formatted version of them i.e. make the formatting in the .go-file and then always display the raw string in a tooltip on hover or something like that.

  • 写回答

2条回答 默认 最新

  • doujiao2443 2014-08-06 15:34
    关注

    You could add a custom truncate function to the FuncMap. Someone posted an example on the playground, which converts template variables to uppercase, like this:

    {{ .Name | ToUpper  }}
    

    Edit. Adjusted above code as a basic Truncate filter: http://play.golang.org/p/e0eaf-fyrH

    {{ .Name | Truncate  }}
    

    If you want to pass a parameter to Truncate, you'll can also write it like this:

    {{ Truncate .Name 3 }}
    

    See also: http://play.golang.org/p/Gh3JY1wzcF

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 复现论文:matlab仿真代码编写
  • ¥15 esp32驱动GC9A01循环播放视频
  • ¥15 惠普360g9的最新bios
  • ¥30 这个功能用什么软件发合适?
  • ¥60 微信小程序,取消订单,偶尔订单没有改变状态
  • ¥15 用pytorch实现PPO算法
  • ¥15 关于调制信号的星座图?
  • ¥30 前端传参时,后端接收不到参数
  • ¥15 这是有什么问题吗,我检查许可证了但是显示有呢
  • ¥15 机器学习预测遇到的目标函数问题