If you have a URL (external to your site) such as http://www.fruit-company.com/some/product/ how can you trim the “http://www ” part and truncate the result, so you get something like fruit-company.com/som … ?
Btw the trimming needs to work for either “http” or “https”.
This is the end result I’m looking for:
{{with .Params.website}}
<a href="{{.}}" target="_blank">fruit-company.com/som...</a>
{{end}}
The following only works for “http” and I couldn’t find a truncation function in the Hugo docs.
{{with .Params.website}}
<a href="{{.}}" target="_blank">{{trim . "http://www-"}}</a>
{{end}}
UPDATE: I just tried doing something like this:
{{trim . "http://www.-" | slicestr 0 20}}
but I get an error “error calling slicestr: start argument must be integer”. Not sure how to pipe the trim result to slicestr without getting this error.
bep
February 8, 2016, 7:29pm
2
Wrap your first argument to slicestr in some parens.
Hmm that doesn’t seem to work.
{{trim . "https://www.-" | slicestr (0 5)}}
at <0>: can't give argument to non-function 0
I’ve tried:
`{{(trim . "https://www.-") | slicestr 0 5}}`
`{{trim . "https://www.-" | slicestr (0) 5}}`
`{{trim . "https://www.-" | (slicestr 0 5)}}`
bep
February 8, 2016, 7:42pm
4
You took my post a little bit too literal …
{{ slicestr (trim . "http://www.-") 0 20}}
Go Template Trivia
In a Go template pipeline, the previous result is passed as the last argument to the next command, so you’re asking the template to execute:
slicestr 0 20 "fruit-company.com/..."
That’s why the pipe isn’t working as you’d expect.
Ah that works. Thanks.
As moorereason pointed out the output is passed as the last argument. Is there any way I can trim http://www . OR https://www . as I can’t chain them link this
{{ slicestr (trim . "http://www.-" | trim "https://www.-") 0 20 }}
Ok I’d have to do this ugly thing:
{{substr (trim (trim . "https://www.-") "http://www.-") 0 20}}
UPDATE: FInally to get the “…” to show that it’s truncated I’d need this:
<a href="">{{substr (trim (trim . "https://www.-") "http://www.-") 0 17}}...</a>
I wish there were cleaner and more intuitive ways of doing small things like this.
bep
February 8, 2016, 8:06pm
8
Hugo is a static site generator, and the template logic is (and should be) limited.
The clean way of doing what you do is to separate the link text and the link URL into two separate fields; then there is no need for this string magic.
It would be cleaner if something like this existed:
{{ replaceRE `^https?://www\.(.{0,17}).*` `$1` .URL }}
func ReplaceRE(pattern, repl, src string) string
Nothing magical about it…unless regexp is new to you, then it does look like magic.
I can work on adding such a func to the funcMap if we like the idea. I vote
1 Like