2

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 %}```
2

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

| improve this answer | |
  • That's brilliant – CreateSean Apr 18 at 12:42
  • @foamcow thanks! i didn't know about that – user9975 Apr 19 at 15:21
1
{% if craft.app.request.segments|length > 1 %}
  {% set secondToLast = craft.app.request.segments|slice(-2, 1)|first %}
{% else %}
  no second to last
{% endif %}
{{ secondToLast }}

getSegments() returns an array of segments

in line 1: check if there is a second to last item

slice(-2, 1): -2 target second to last item and you only that one so second parameter is 1

|first is because slice returns an array


this solution need some tests and some consideration for example Craft docs says:

Note that the segments will not include the control panel trigger if it’s a control panel request, or the page trigger or page number if it’s a paginated request.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.