Skip to content

Instantly share code, notes, and snippets.

@fyrebase
Last active April 18, 2018 13:50
Show Gist options
  • Save fyrebase/948cf229077f0bac832e to your computer and use it in GitHub Desktop.
Save fyrebase/948cf229077f0bac832e to your computer and use it in GitHub Desktop.
Neat way of adding active class to cached navigation in Craft - From http://goo.gl/9LaOuM
{% set navigation %}
{% cache globally for 3 years %}
{% set entries = craft.entries.section('navigation') %}
<ul>
{% nav entry in entries %}
<li>
{# Check for entry type / get related entry #}
{% if entry.type == 'linkedChannelEntry' %}
{% set linkedEntry = entry.entriesField.limit(1).first() %}
{% endif %}
{% if linkedEntry %}
{# Link to a linked channel entry #}
<a href="{{ linkedEntry.url }}" data-url="{{ linkedEntry.url }}">{{ linkedEntry.title }}</a>
{% else %}
{# Link to a structure entry #}
<a href="{{ entry.url }}" data-url="{{ entry.url }}">{{ entry.title }}</a>
{% endif %}
{# Repeat this for child entries #}
{% ifchildren %}
<ul>{% children %}</ul>
{% endifchildren %}
</li>
{% endnav %}
</ul>
{% endcache %}
{% endset %}
{{ navigation|replace({('data-url="' ~ craft.request.getUrl() ~ '"'): 'class="active"'})|raw }}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment