1

I have a macro that can take up to six parameters which serve to populate nav links. The parameters are basically grouped into twos, with someone needing to pass in both a link and a title to make a nav link.

Below is my current code, which works as intended, but is not very DRY.

{% macro mobileNav(navLink1, navTitle1, options={}) %}

{% import _self as self %}

  {% set options = {
    navLink2: null,
    navTitle2: null,
    navLink3: null,
    navTitle3: null,
    navClass: '',
    navItemClass: ''

  }| merge(options) %}

  <nav {% if options.navClass | length %}class="{{ options.navClass }}"{% endif %}>

    <ul>

      {% if navLink1 | length %}
        <li {% if options.navItemClass | length %}class="{{ options.navItemClass }}"{% endif %}>
          <a href="{{ navLink1 }}">{{ navTitle1 }}</a>
        </li>
      {% endif %}

      {% if options.navLink2 | length %}
        <li {% if options.navItemClass | length %}class="{{ options.navItemClass }}"{% endif %}>
          <a href="{{ options.navLink2 }}">{{ options.navTitle2 }}</a>
        </li>
      {% endif %}

      {% if options.navLink3 | length %}
        <li {% if options.navItemClass | length %}class="{{ options.navItemClass }}"{% endif %}>
          <a href="{{ options.navLink3 }}">{{ options.navTitle3 }}</a>
        </li>
      {% endif %}

    </ul>

  </nav>

{% endmacro %}

I would like to DRY it out and have one list element where the number associated with the parameter dynamically increases.

Something like this (with the flexibility to an argument being passed via options as well):

 {% if navLink(a number between 1 & 3 that is passed in) | length %}
        <li {% if options.navItemClass | length %}class="{{ options.navItemClass }}"{% endif %}>
          <a href="{{ navLink(a number between 1 & 3 that is passed in) }}">{{ navTitle(a number between 1 & 3 that is passed in) }}</a>
        </li>
      {% endif %}

I haven't been able to figure out how to make it work though. Any help would be appreciated. Thanks!

2

Why don't you pass an array as a parameter?

{% macro mobileNav([
    {url: '/1', title: 'Foo'},
    {url: '/2', title: 'Bar'},
    {url: '/3', title: 'FooBar'},
], {} ) %}

And in your macro..

{% for item in items %}
    {% if item.title is defined and item.title is not empty and item.url is defined and item.title is not empty %}
         // ... output something
         <a href="{{ item.url }}">{{ item.title }}</a>
         {{ items|length <= 3? 'less than 4' : 'more than 3 are passed' }}
    {% endif %}
{% endfor %}
| improve this answer | |
  • That was the ticket! Thank you so much for the suggestion - that solved the problem. – dpayne Jul 5 '18 at 20:46

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.