Craft CMS Asked by DieselHashtag on May 12, 2021
I’m currently using the below jQuery but it’s buggy as it relies on looking for ‘similar’ URL and not the exact URL.
Is there a way it can be done just using Twig?
{% set mainNavigation = craft.entries.section('mainNavigation').all() %}
<div class="navbox-collapse collapse" id="navbar-menu">
<ul class="nav" data-in="fade-In-Down" data-out="fade-Out-Up">
{% nav page in mainNavigation %}
<li class="{% if page.hasDescendants() %}topLevel dropdown {% else %}singleLevel{% endif %}">
{% if page.customUrl|length %}
<a {% if page.hasDescendants() %} class="dropdown-toggle" data-toggle="dropdown" {% endif %} href="{{ page.customUrl }}"><span>{{ page.title }}</span></a>
{% else %}
<a {% if page.hasDescendants() %} class="dropdown-toggle pageLink" data-toggle="dropdown" {% endif %} href="{{ page.selectEntry.one().url }}"><span>{{ page.title }}</span></a>
{% endif %}
{% ifchildren %}
<ul class="dropdown-menu megamenu-content {% if page.doubleColMenu.contains('twoxcol') %}twoxcol {% endif %}">
{% children %}
</ul>
{% endifchildren %}
</li>
{% endnav %}
</div>
<script type="text/javascript">
$(function(){
var current = location.pathname;
$('#navbar-menu li a').each(function(){
var $this = $(this);
// if the current path is like this link, make it active
if($this.attr('href').indexOf(current) !== -1){
$this.addClass('active');
}
})
})
</script>
You don't need to use Javascript/jQuery for this.
You can get the the current url from craft.app.request
in some way and do a check as you output your navigation.
It looks like you have some custom fields for urls but, For instance, if you wanted to check the last url segment you could use craft.app.request.segment(-1)
to get it. Then when outputting your css classes, check it against whatever and output the active class.
{% set currentPage = craft.app.request.segment(-1) %}
then in your loop...
<li class="{{ thisUrl == currentPage ? 'active ' }} otherclasses">
<a href="{{ foo }}>Some title</a>
</li>
You can also get the full URL with {{ craft.app.request.absoluteUrl }}
Or {{ craft.app.request.pathInfo }}
to get the path
Answered by foamcow on May 12, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP