[SOLVED] Add .HasSuffix function


#1

Now that we have /assets pipelines an issue I’ve been running into is ranging over a mixture of media types and not being able to resize or modify them. The main culprit here is SVG’s – which I agree doesn’t particularly need resizing capabilities – but if an SVG gets mixed in within a typical jpg’s or pngs hugo fails to build.

Here’s my scenario

{{ range where .Site.RegularPages "Section" "customers" }}
    {{ $logo := resources.Get (printf "%s" .Params.logo) }}
{{ end }}

Now if one wants to modify the resource to fit the space better, they may run into an issue if there’s a reference to a media type that cant be modified, like an SVG.

So since we already have .HasPrefix maybe also having .HasSuffix would be useful especially to prevent this type of issue from happening.

For example…


{{ range where .Site.RegularPages "Section" "customers" }}
    {{ $logo := resources.Get (printf "%s" .Params.logo) }}
    {{ if ne .HasSuffix "svg" }}
        {{ $resize := $logo.Resize "140x" }}
        <!-- Modified resource -->
        <img src="{{ $resize.RelPermalink }}" width="{{ $logo.Width }}">
    {{ else }}
        <!-- unmodified resource -->
        <img src="{{ $logo.RelPermalink }}" >
    {{ end }}
{{ end }}

#2

There is a strings.HasSuffix you can use.


#3

Oh wow I didn’t know that existed! Does this mean we have the GO strings package available to us even if it’s not included in the Hugo docs, like contains?

And for anyone that comes across this with the same problem here is how I did it

{{ if ne (strings.HasSuffix .Params.logo "svg") true}}
...
{{ else }}
...
{{ end }}

#4

Not all of it – we used the same signature for most of them – but with argument order switched to make them “pipe friendly” … https://godoc.org/github.com/gohugoio/hugo/tpl/strings


#5

@Randy_Lough You should always check the list of functions available here: https://gohugo.io/functions.

There are a handful of strings.* functions available but I suspect not all, and some function names follow the Go naming convention, e.g. strings.RuneCount, while others don’t, e.g. replace (which is an alias for strings.Replace).


#6

Ah very cool! I’ll check out the godoc page in more detail and see what other gems I can find. Thanks!


#7

@lucperkins I obviously did check out the docs first, which strings.HasSuffix isn’t part of or even ever mentioned in any context. I don’t think this thread is that far out of left field? Especially since I’ve never seen it mentioned in the docs (or here) that there’s GO functions available to us outside of Hugo’s documentation.

Might be worthwhile mentioning that link in the https://gohugo.io/functions overview section and again in the strings.* area


#8

This should be the same:

{{ if not (strings.HasSuffix .Params.logo “svg”) }}


#9

Yeah that’s way more readable