Get the last part from URL

This article is a quick tip if you need to grab the last piece from a URL. Very handy one liner if you require grabbing the current section, taxonomy tag, or similar.

I’m in hurry - show me the code.

For a quick copy paste the statement first:

{{ $lastUrlElement := index (last 1 (split (delimit (split .URL "/") "," "") ",")) 0 }}

What it does? Step, by step.

Let’s assume we are on a URL called /tags/mytag/ it returns mytag as a string.

First, it splits the URL into pieces and returns an array:

{{ $justTheSplit := split .URL "/" }}
<!-- $justTheSplit := ["", "tags", "mytag", ""] !-->

Now to get rid of the last empty element a trick with the last parameter comes into place:

{{ $aStringWithoutLastEmpty := delimit (split .URL "/") "," "" }}
<!-- $aStringWithoutLastEmpty := ",tags,mytag" !-->

Next, we split this again to get the desired part at the end of the list:

{{ $arrayAgain := split (delimit (split .URL "/") "," "") "," }}
<!-- $arrayAgain := [",", "tags", "mytag"] !-->

Next, we isolate the last part of the array:

{{ $lastPartOnly := last 1 (split (delimit (split .URL "/") "," "") }}
<!-- $lastPartOnly := ["mytag"] !-->

Last we transform the element into a string grabbing the element at index zero.

{{ $tag := index (last 1 (split (delimit (split .URL "/") "," "")) 0 }}
<!-- $tag := "mytag" !-->

Ideal use case

This way is a common use case in list templates, where you need to filter the next data dynamically. I use this method very often to filter a list of current taxonomy or to check in which section I am, like this:

{{ $currentTag := index (last 1 (split (delimit (split .URL "/") "," "") ",")) 0 }}
{{ $tagPages := index .Site.Taxonomies.tags $currentTag }}

Pagination

With paginations, let us assume a URL like this /tags/mytag/page/4/. In this case you still get mytag returned because we calculated the last piece where the URL still ended with mytag.

So this still works:

{{ $currentTag := index (last 1 (split (delimit (split .URL "/") "," "") ",")) 0 }}
{{ $tagPages := index .Site.Taxonomies.tags $currentTag }}
{{ $paginator := .Paginate $tagPages 10}}

<ul>
{{ range $paginator.Pages }}
    <a href="{{ .RelPermalink }}">{{ .Title }}</a>
{{ end }}
</ul>

{{ $pag := $.Paginator }}
{{ if gt $pag.TotalPages 1 }}
  <ul>
        {{ range $pag.Pagers }}
        <li {{ if eq . $pag }}class="active"{{ end }}><a href="{{ .URL }}">{{ .PageNumber }}</a></li>
        {{ end }}
  </ul>
{{ end }}

Okay, what’s with the root?

If you use this on the index page like https://example.com/, it silently returns an empty string.