Make my code terser: how to get last segment of the .Permalink


Derived my /categories/category_name permalink, I’d like to use the value of category_name to affect my where invocation within the logic of my taxonomy.html file so that only posts of category_name show up. Clearly a call for where.

But I was surprised that there was no way to easily extract category_name. I would have thought it would have been easier than what’s suggested here. I modified this idea (in a very ugly fashion) and I was wondering whether someone might suggest a more succinct way to do what I’m doing.

      {{ $subsection := slice (index (last 1 (split (delimit (split .Permalink "/") "," "") ",") ) 0 | humanize) }}
      {{ range where .Pages.ByDate "Params.categories" "intersect" $subsection }}

Thus for /categories/microblog, $subsection becomes ["Microblog"] which can be used to intersect the Pages whose categories value in their front-matter matches ["Microblog"]. Is there a place for cleanup here? In Ruby I wouldwrite something like:


Is there a way to get closer to that level of concision?

Checkout the urls.Parse function. You could get the .Path of the URL and work with it from there.

Yep, this got the line down to something a little less Lisp-y looking. Thanks.

Good deal. Would you share your new and improved solution? I’m sure this thread will be looked at again.

1 Like

For the record, here is my invocation. I’ve tried to keep readability high b/c I hope to not write templates very often :wink:

     {{ $urls := urls.Parse .Permalink }}
      {{ $subs := slice (index (split $urls.Path "/") 2 | humanize) }}
      {{ $paginator := .Paginate (where .Pages.ByDate "Params.categories" "intersect" $subs) 20 }}
      {{ range $paginator.Pages }}
        <div class="relative w-100  mb4 bg-white">
          {{ partial "summary.html" . }}
      {{ end }}
    {{ template "_internal/pagination.html" . }}

E.g. {{ .RelPermalink | path.Base }}

Even better :slight_smile:

Aw, shucks, @bep, that takes the cake.