I'm using a macro to check segment 1 to set an active state on my navigation and all is working correctly. However I would like to change it so that if segment_2 is not empty it doesn't display the active state, with the exception of being pagination in segment-2

so domain.com/photography and domain.com/photography/p2 would get active but domain.com/photography/slug would not be active

my current code is:


{% macro is_active(segment) %}{% if craft.request.firstSegment == segment %}active{% endif %}{% endmacro %}

and nav:

<ul class="nav navbar-nav">
  <li class="{{ macro.is_active('') }}"><a href="/">Home</a></li>
  <li class="{{ macro.is_active('photography') }}"><a href="/photography">All Photography</a></li>
  <li class="{{ macro.is_active('calendar') }}"><a href="/calendar">Archives</a></li>

Not tested, but I think you can test if it is a pagination page. So

{% if (craft.request.getSegment('2') == '') or (craft.request.getPageNum() != 1) %}active{% endif %}
| improve this answer | |

Here is a possible macro. It uses getSegment() to get the second segment, and twig's matches operator to compare that segment to the page trigger. Note that there is a pageTrigger setting, and this macro assumes you haven't changed that trigger.

{% macro is_active(segment) %}
  {% set firstSeg = craft.request.getSegment(1) %}
  {% set secondSeg = craft.request.getSegment(2) %}
  {# is secondSeg a pagination segment? #}
  {% set isPagination = secondSeg and secondSeg matches '/^p[0-9]+/' %}

  {# active: firstSeg is our segment, and no secondSeg, or secondSeg is pagination seg #}
  {% if firstSeg == 'segment' and (not secondSeg or isPagination) %}
  {% endif %}
{% endmacro %}

You might also want to use the twigperversion plugin which provides a {% return %} tag:

{% macro is_active(segment) %}
  {% return firstSeg == 'segment' and (not secondSeg or isPagination) %}
{% endmacro %}

and then {{ macro.is_active('photography') ? 'active' }}

| 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.