1

I am trying to create a reusable component with a set a default variables that can be overridden when included in a template:

includes/social.twig

{% set padding, size, color, hover = '2', '4', 'pink', 'black' %}

<ul>
  <li class="px-{{ padding }} text-{{ size }}">
    <a class="text-{{ color }} hover:text-{{ hover }}" href="{{ contactDetails.link }}">
      <i class="fab fa-link"></i>
    </a>
  </li>
</ul>

page.twig

{% include '_includes/social-links.twig' with {
  padding: '10',
  size: '2',
  color: 'blue',
} %}

When using this, variables that haven't been set in the include statement would remain as defined in the include file, and those that have would override the variables set in the include file. This doesn't happen - nothing gets overridden.

I can achieve a working version of this using:

includes/social.twig

<ul>
  <li class="px-{{ padding }} text-{{ size }}">
    <a class="text-{{ color }} hover:text-{{ hover }}" href="{{ contactDetails.link }}">
      <i class="fab fa-link"></i>
    </a>
  </li>
</ul>

page.twig

{% set padding, size, color, hover = '2', '2', 'blue', 'black' %}
{{ include('_includes/social-links.twig') }}

This involves not setting the vars in the include file, but setting them in the page template - this approach seems more error prone and less maintainable than the version I am trying to achieve.

2

There is no reason why your code should work, because any variable declared outside of your include file in the with {...} block will be immediately overwritten by your variable definition (#set) in the beginning of your included file.

What you need to do in your include is to check, if the variable was passed in from the outside, and if not, set it to a default value.

So I guess the best way could be this in your includes/social.twig file:

{% set padding, size, color, hover = padding ?? '2', size ?? '4', color ?? 'pink', hover ?? 'black' %}

<ul>
  <li class="px-{{ padding }} text-{{ size }}">
    <a class="text-{{ color }} hover:text-{{ hover }}" href="{{ contactDetails.link }}">
      <i class="fab fa-link"></i>
    </a>
  </li>
</ul>

The ?? used here is called the null-coalescing operator. It will check if the variable before the ?? is defined (which it is if provided from the outside) and in case it's not not, fall back to the value after it. Have a look here, if you do not know it: https://straightupcraft.com/events/twigs-null-coalescing-operator

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