Golang: how to approach string formatting in templates
I am passing structure to a template that sometimes contains strings that are too long to display. In any other language, I would just apply the formatting rule in the template itself. What's the idiomatic approach to 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 do to make sure that .anotherThing or .something doesn't display more than 40 characters?
One solution should be for the structure to contain four values, two raw strings, and two formatted versions, i.e. did the formatting in a .go file and then always display the raw string in the tooltip on hover or something.
source to share
You can add a custom truncate function to FuncMap . Someone posted an example on a playground that converts template variables to uppercase, like this:
{{ .Name | ToUpper }}
Edit. Adjusted above code as main filter Truncate
: http://play.golang.org/p/e0eaf-fyrH
{{ .Name | Truncate }}
If you want to pass a parameter Truncate
, you can also write it like this:
{{ Truncate .Name 3 }}
See also: http://play.golang.org/p/Gh3JY1wzcF
source to share
One approach, besides using a custom function, is defining your own type with an interface Stringer
:
type ShortString string
func(ss ShortString) String() string {
if len(ss) > 10 {
return string(ss[:5]) + "..."
}
return string(ss)
}
type MyStruct struct {
Something ShortString
}
playgroundshowing both approaches.
source to share