For more advanced sites built using Pages, you may want to adjust the output of a custom HTML or PHP block depending on the page being viewed. For example, you may have a custom menu where you want to highlight the current active section.
Checking Path Parameters
This can be achieved within Pages by checking the underlying page URL parameters. While visitors access pages using friendly URLs (FURLs), such as:
http://<yourcommunity>/section/page
Behind the scenes, this is mapped to a raw URL containing additional information, for example:
http://<yourcommunity>/index.php?app=cms&module=pages&controller=page&path=/section/page
The path parameter identifies the page currently being accessed. By checking this value through the \IPS\Request::i() object, you can compare against the current page and adjust your block output accordingly.
{{if strpos( \IPS\Request::i()->path, 'section/page' ) !== FALSE}}
<!-- We know the user is on /section/page -->
{{elseif strpos( \IPS\Request::i()->path, 'othersection/otherpage' ) !== FALSE}}
<!-- We know the user is on /othersection/otherpage -->
{{endif}}For improved reliability, we use PHP’s strpos function to check whether the page URL exists within the path parameter, rather than performing a direct comparison.
This allows the check to match the relevant page path more flexibly and ensures the correct output is displayed when the condition is met.
Working Example
As an example, let’s say we have created a Manual HTML block containing a custom menu, and we want the menu to highlight the correct item depending on the page the visitor is currently viewing.
The contents of the block may look something like the following:
<ul class='ipsList_inline cMyMenu'>
<li {{if strpos( \IPS\Request::i()->path, 'help/home' ) !== FALSE}}class='active'{{endif}}>
<a href='/help/home'>Home</a>
</li>
<li {{if strpos( \IPS\Request::i()->path, 'help/faq' ) !== FALSE}}class='active'{{endif}}>
<a href='/help/faq'>FAQ</a>
</li>
<li {{if strpos( \IPS\Request::i()->path, 'help/tutorials' ) !== FALSE}}class='active'{{endif}}>
<a href='/help/tutorials'>Tutorials</a>
</li>
</ul>If we had many items to show, it would get tedious to list them all like this. We could instead do it as a loop:
// Using a PHP variable to store an array of pages => page names that we'll loop over
{{$myPages = array('help/home' => "Home", 'help/faq' => "FAQ", 'help/tutorials' => "Tutorials", 'help/qna/listing' => "Questions", 'help/qna/recent' => "Recent Questions", 'help/contact' => "Contact Us");}}
<ul class='ipsList_inline cMyMenu'>
{{foreach $myPages as $url => $title}}
<li {{if strpos( \IPS\Request::i()->path, $url ) !== FALSE}}class='active'{{endif}}>
<a href='{$url}'>{$title}</a>
</li>
{{endforeach}}
</ul>Now to add new items to our custom menu, we just have to add them to the array.
Recommended Comments