String Utilities?

Please excuse my unfamiliarity with Go and Go Templates.

Is there a mechanism from within a template or shortcode to access basic string functions?

For example, it would be great to be able to trim whitespace from a String. Or to do a substring.

Unfortunately, Go standard template doesn’t have such functions so we have to implement them by ourselves to use them in a template. I think trim is useful and substring would be. Do you have other function examples?

Other usefull functions could be (php function names) :

ucfirst
ucwords
implode
explode

I have a PR that adds chomp (removes trailing newlines) for some other purpose.

@halostatue What PR includes chomp? I’ve thought a lot of times that I’d like to remove all empty newlines from some of my partial templates. I hate how making the code more readable with the templating system introduces massive amounts of whitespace, but I haven’t seen a way around it. I’d love to be able to pipe my partial output through a command that deletes newlines.

Or add the spiritual equivalent of m4’s dnl.

As Hugo cannot implement all of them (I know many of them exist in Go, but a Template wrapper has to be added), maybe some of you could find a suitable voting site to put all of these suggestions … Then after n days, the top m functions would be added …

I did, but I’m not sure I did it correctly.

Would nice to be able to vote for more than one.

1 Like

chomp is included in the apply PR, because otherwise {{ delimit (apply . "partial" "post/tag/link" ".") ", " }} results in a , b , c instead of a, b, c (note the spaces before the commas in the first list).

I have implemented a “trim” function that trims whitespace AND newlines, but I have no good name for it. It’s what I think I would need in most Hugo cases.

newline trimming is what I’m most interested in. That will help partials be much more expressive instead of trying to cram everything onto one line.

1 Like

The chomp function does exactly the newline trimming, and it’s in place with the latest HEAD because my apply function has been merged. (It’s called chomp because that’s the name I know this under, all the way back to when I learned Perl.) I think that trim should only deal with whitespace (trim: both left and right; ltrim: left only; rtrim: right only).

@bjornerik, do these functions work well with the Ace templates?

@halostatue yes, these works fine with Ace templates.

I kind of agree with you about the naming, but in my case I have the need for this ugly construction:

{{ $someText | chop | chomp | trim }}

And even that isn’t the same as my “supertrim”.

@fredxinfan has just submitted a pull request for substr and split too, see https://github.com/spf13/hugo/pull/990