2

I have the following in my routes.php file:

return array(
    'articles/(?P<sectionId>\d+)/(?P<offset>\d+)' => 'articles/index'
);

And while localhost/articles/4/1, for example, routes properly to the template, localhost/articles/4/0 does not and I instead get a 404.

Is there an issue with zeros being picked up as valid URI segments?

2

An easy fix could be to define an additional route without the offset parameter:

return array(
    'articles/(?P<sectionId>\d+)' => 'articles/index',
    'articles/(?P<sectionId>\d+)/(?P<offset>\d+)' => 'articles/index',
);

In your template, you'd need to check if the offset parameter is defined, and if not, set it to 0:

{{ offset | default( 0 ) }}

or

{% set offset = offset is defined ? offset : 0 %}

EDIT:

Another way to solve this is by making the offset segment capturing group optional, as per @carlcs' answer to this question – in my opinion this is a bit more elegant than having two different routes:

return array(
    'articles/(?P<sectionId>\d+)(/(?P<offset>\d+))?' => 'articles/index',
);

The trick here is wrapping the last segment in parentheses, appending a question mark at the end.

2
  • 1
    Mats, probably a good workaround. Just wanted to add that there's also this ternary syntax possible: {% set offset = offset is defined ?: 0 %}.
    – carlcs
    Mar 7 '15 at 11:43
  • @carlcs – Nice one, even more succinct :) Mar 7 '15 at 12:06

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.