如何截断Golang模板中的字符串 [英] How to truncate a string in a Golang template

查看:369
本文介绍了如何截断Golang模板中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在golang中,是否可以截断html模板中的文本?

例如,我的模板中包含以下内容:

  {{range .SomeContent}} 
....
{{.Content}}
... 。

{{end}

{{ .Content}} 产生:Interdum et malesuada fames ac ante ipsum primis in faucibus。 Aliquam tempus sem ipsum,vel accumsan felis vulputate id。 Donec ultricies sem purus,non aliquam orci dignissim et。整数简历。 Pellentesque a ipsum quis velit venenatis vulputate vulputate ut enim。



我想将其缩减为25个字符。

printf ,它充当 fmt.Sprintf 。在你的情况下,截断一个字符串可能很简单:

 {{printf \%。25s \。内容}}


In golang, is there a way to truncate text in an html template?

For example, I have the following in my template:

{{ range .SomeContent }}
 ....
    {{ .Content }}
 ....

{{ end }

{{ .Content }} produces: Interdum et malesuada fames ac ante ipsum primis in faucibus. Aliquam tempus sem ipsum, vel accumsan felis vulputate id. Donec ultricies sem purus, non aliquam orci dignissim et. Integer vitae mi arcu. Pellentesque a ipsum quis velit venenatis vulputate vulputate ut enim.

I would like to reduce that to 25 characters.

解决方案

You can use printf in templates, which acts as fmt.Sprintf. In your case truncating a string would be as easy as:

"{{ printf \"%.25s\" .Content }}"

这篇关于如何截断Golang模板中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆