× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Golang: How to approach string formatting in templates

Martin Czygan
May 05, 2015
<p>You could add a custom truncate function to the <a href="http://golang.org/pkg/text/template/#FuncMap" rel="nofollow">FuncMap</a>. Someone posted an <a href="http://play.golang.org/p/z-yyM6mVt8" rel="nofollow">example</a> on the playground, which converts template variables to uppercase, like this:</p> <pre><code>{{ .Name | ToUpper }} </code></pre> <p>Edit. Adjusted above code as a basic <code>Truncate</code> filter: <a href="http://play.golang.org/p/e0eaf-fyrH" rel="nofollow">http://play.golang.org/p/e0eaf-fyrH</a></p> <pre><code>{{ .Name | Truncate }} </code></pre> <p>If you want to pass a parameter to <code>Truncate</code>, you'll can also write it like this:</p> <pre><code>{{ Truncate .Name 3 }} </code></pre> <p>See also: <a href="http://play.golang.org/p/Gh3JY1wzcF" rel="nofollow">http://play.golang.org/p/Gh3JY1wzcF</a></p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/25164392/Golang:%20How%20to%20approach%20string%20formatting%20in%20templates/25164518">Stack Overflow</a>.</p>
comments powered by Disqus