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

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.

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

One approach besides using a custom function is defining your own type with the Stringer interface:

type ShortString string

func(ss ShortString) String() string {
    if len(ss) > 10 {
        return string(ss[:5]) + "..."
    }
    return string(ss)
}

type MyStruct struct {
    Something    ShortString
}

playground displaying both approaches.