$URLSegment and $InSection() not working on any other .ss file other than Page.ss?

Silverstripe Version: 4.8.0

How can I make $URLSegment and $InSection(about) work in an include file?

I wanted to assign a class depending on the URLSegment which works perfectly fine in Page.ss.
I tried it on any other pages e.g. HomePage.ss or an included .ss file where I actually only want to use it, but it doesn’t work.
I guess this is intended then or is there anything else I can use to get the last part of the url in other .ss files than the Page.ss?

I know I can work around this and use it on Page.ss level, but I wanted to know if there is a different way as I only need it in one particular case.


Hi Kimk

You should be able to have access to URLSegment provided the Includes file is called within the scope of the page.

If you have called the include file from a different scope and are trying to access the URLSegment via $Top.URLSegment or $Up.URLSegment then this will not work.

If that is the case, try passing either the URLSegment or the Page itself to the includes file like this:

// option 1
<% include MyIncludesFile PageScope=$Top %>
// option 2
<% include MyIncludesFile URLSegment=$Top.URLSegment %>

Then in your includes file you can go

// option 1 ($PageScope being the Page, so all methods and fields are available)
// option 2