0

Doing my first site with Craft and UiKit framework I encountered a small problem with dropdown menu. Here is my code:

<ul>
  {% set entries = craft.entries.section('spb') %}
  {% nav entry in entries %}
  <li class="uk-parent" data-uk-dropdown>
    <a {% if craft.request.getPath() == entry.uri %} class="active" {% endif %} href="{{ entry.url }}">{{ entry.title }}</a>
    {% ifchildren %}
    <div class="uk-dropdown">
      <ul class="uk-nav uk-nav-dropdown">
        {% children %}
      </ul>
    </div>
    {% endifchildren %}
  </li>
  {% endnav %}
</ul>

The point is that my child element looks exactly like parent because it takes its structure. But I don't need neither "class" nor "data-uk-dropdown" element...

<li class="uk-parent" data-uk-dropdown=""><a href="#">...</a></li>

Is there any workaround? Thanks.

1 Answer 1

2

You can use entry.level in a conditional:

{% set entries = craft.entries.section('spb') %}
{% nav entry in entries %}

    {% set liTagAttributes = entry.level == 1 ? 'class="uk-parent" data-uk-dropdown' : 'class="uk-child"' %}

    <li {{ liTagAttributes|raw }}>
        <a href="{{ entry.url }}">{{ entry.title }}</a>
        {% ifchildren %}
            ...
        {% endifchildren %}
    </li>

{% endnav %}

I set a intermediate var to keep the template code clean. If you don't have many levels in your structure, you could also consider to not use the nav tag at all and nest your navigation levels using hasDescendents and getDescendents(1) (see the example code I posted here).

5
  • Very useful tip! Thank you. By the way, you don't need to use double quotes in {% set liTagAttributes = entry.level == 1 ? 'class=uk-parent data-uk-dropdown' : 'class=uk-child' %} Dec 18, 2014 at 9:27
  • Errrm, this wasn't for the Twig code but to make it return valid HTML for setting the CSS class, @Stanislav.
    – carlcs
    Dec 18, 2014 at 9:31
  • Sure, but if you leave them it returns two times double quotes ""..."" Dec 18, 2014 at 9:37
  • Sorry, you were right. HTML5 does indeed allow you to NOT wrap attribute values in quotes.
    – carlcs
    Dec 18, 2014 at 9:37
  • @Stanislav forgot to add the raw filter to the output. This makes Twig to not escape the code and you end up with single quotes. I definitely don't recommend to use attribute value without quotes at all.
    – carlcs
    Dec 18, 2014 at 9:43

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.