How to get second last url segment I'm setting up a dynamic thank-you page for all forms added to the site. Client can add forms with freeform to any page and I have set the return url to this:

{{ form.renderTag({
    class: "w-full pb-4",
    returnUrl: craft.app.request.absoluteUrl ~ 'thank-you/'
    }) }}


Which works. However on the thank-you page I would like to set the entry to be the slug of the second last url segment

i.e. if the thank you page is https://domain.com/foo/bar/thank-you then I need to be able to get bar however if the url is https://domain.com/foo/thank-you then I need to get foo

How can I do this? if only craft.app.getSecondLastSegment() were a thing.

so ideally something simpler than this:

{% set entrySlug = "" %}

{% if craft.app.request.getSegment('4')|length %}
  {% set entrySlug  = craft.app.request.getSegment('3') %}
{% elseif craft.app.request.getSegment('3')|length %}
  {% set entrySlug  = craft.app.request.getSegment('2') %}
{% elseif craft.app.request.getSegment('2')|length %}
{% else %}
  {% set entrySlug  = craft.app.request.getSegment('1') %}
{% endif %}```
You can use negative numbers as the parameter for segment which then counts from right to left.

So {{ craft.app.request.segment(-1) }} will get the last segment.

And... {{ craft.app.request.segment(-2) }} will get the next to last segment