[Solved] More String Utilities?

I encounter some problems to handle strings when working with the “shortcodes” variable {{ .Inner
}}

  1. How to use a escape newline character “/n” in go template ?
    {{ delimit (slice “foo” “bar” “buzz”) “/n” }} dosen’t work as I expected to get three lines.

  2. How to remove the leading newline characters “/n” ?
    "/nHello world!" -> “Hello world!”

  3. How to concatenate a string constant and a string variable in one step directly ?
    {{ $prefixed := delimit (slice “bar” .Title) “” }}
    It looks strange to do this with the function delimit. I’d prefer a new function concat()
    {{ concat “bar” .Title }}

  4. How to count number of lines in a string ?
    “foo/nbar/nbuzz” => three lines

is there a easier way to do these ? thank you ~

You’re using the wrong slash in this post, but I’ll assume that’s just a typo.

  1. {{ printf "%s\n%s\n%s\n" "foo" "bar" "buzz" }}

  2. {{ replace "\n" "" "\nHello world!" }}

  3. {{ prefixed := (printf "%s%s" "bar" .Title) }}

  4. {{ split "foo\nbar\nbuzz\n" "\n" | len }}

2 Likes

point 2. what if there are more than one “\n” but only the leading one should be removed ?

“\nHello world!\nBar” -> “Hello world!\nBar”

thanks for your guidance ~ :yum:


I have found a possible solution : substr

a lot of Inspiration ~ Thanks for your help

We also have replaceRE. It’s probably overkill, but it’s about all we have now.

I would advocate that we add many of the Trim* fuctions from the strings package:

These would ease some of the convoluted things we have to do when wanting manipulate strings in templates. I’m assuming most people are using replaceRE to solve most of these problems, which is slower than these simple trim funcs.

If we had these trim funcs, the solution to #2 would be {{ trimSpace "\nHello world!\nBar" }}, or {{ trim "\n" "\nHello world!\nBar" }} if you didn’t want to trim other whitespace chars.

@bep, what do you think?

I think there is a danger of Hugo ending up being a Turing complete programming language; I’m a little bit surprised about the amount of string manipulation people need to do.

I think this should linger and wait until Hugo 0.20 or something. We need to get the code org. into better shape, so we can better put these funcs into its proper place.

3 Likes