Skip to content
Grav 2.0 is officially stable. Read the announcement →
Archive

Get URI segment data

Started by Muut Archive 10 years ago · 4 replies · 497 views
10 years ago

Is it possible to get URI segment data from Grav? E.g. if I have a page on a site like this:

TXT
www.mysite.com/folder/page/item/

I want to get segment data for that page - so segment 1 == folder, segment 2 == page etc. Then I can do something like:

TXT
if segment2 exists then show sub nav

Etc... thanks

10 years ago

Hi, in Twig you can reference grav.uri.paths and that will return an array of the segments found in the URL

So you can check for example {{dump("folder" in grav.uri.paths)}}

10 years ago

Hi, yeah ok so that gives me this:

JS
array:2 [
  0 => "test"
  1 => "test-child"
]

If i'm at /test/test-child... but how can I use that in a twig variable? E.g:

TWIG
{% if segment_0 == "test" %} foo
10 years ago

Ok so I go this working:

TWIG
{% if grav.uri.paths.0 == "test" %} do something {% endif %}

But this doesn't work - any ideas?

TWIG
{% if grav.uri.paths.count() > 0 %} this has a child {% endif %}
10 years ago

And got it...

TWIG
{% if grav.uri.paths.0 %} do something {% endif %}

Suggested topics

Topic Participants Replies Views Activity
Archive · by Deleted User, 9 years ago
0 1357 9 years ago
Archive · by Muut Archive, 9 years ago
2 936 9 years ago
Archive · by Muut Archive, 9 years ago
2 4066 9 years ago
Archive · by Muut Archive, 9 years ago
1 2955 9 years ago
Archive · by Muut Archive, 9 years ago
3 1121 9 years ago