Aaron Lauterer

Get last and first element in a URL

While working on this website with HUGO I needed the first and last element of the current URL in variables at some point.

There is a snippet available to get the last element in a URL that does some delimit and split magic.

When looking into how to get the first element I came up with another way to also get the last element that might be a bit more understandable.

Snippets

To get the first element:

{{ $firstUrlElement := index (split .URL "/") 1 }}

The last element can be aquired with this snippet:

{{ $lastUrlElement := index (split .URL "/") (sub (len (split .URL "/")) 2) }}

Explanation

Let's look at what we get with split .URL "/" for the url http://website.tld/tags/hugo:

{{ printf "%#v" (split .URL "/") }}
<!-- string{"", "tags", "hugo", ""}  -->

We get an array with 4 elements. The first and last element of that array are strings of zero length. Getting the first URL element is simple. We have to use the index function and tell it to get the second element of the array. Since the numbering starts with 0 this results in index (...) 1.

This was the easy part because we always know at which place the first element of the URL will be. More interesting is how to get the last one!

My approach is this:

  1. get the length of the array
  2. subtract 2
    • 1 to account for the last empty string element in the array
    • +1 to adjust the length to the 0 based numbering
  3. hand the value over to the index function
{{ $lastUrlElement := index (split .URL "/") (sub (len (split .URL "/")) 2) }}
                                               |     |                 | |
                                               |     --- returns 4 ----- |
                                               --- subtracts 2 from 4 ----

Errors?

I tried the snippets on the root level (index.html) and they retured zero length strings "".

Got any hints or questions? blog@aaronlauterer.com