twig-tips

Scoping with for and with

Nope…

{% if entry.assetsField.exists %}
  <img src="{{ entry.assetsField.one().url }}" alt="">
{% endif %}

Yep!

{% for asset in entry.assetsField.limit(1).all() %}
    <img src="{{ asset.url }}" alt="">
{% endfor %}

Nope…

  {% set featuredImgSrc = 'resources/nope.jpg' %}
  {% set featuredImgAlt = 'Nope' %}
  <img src="{{ featuredImgSrc }}" alt="{{ featuredImgAlt }}">

Yep!

{% with {
  src: 'resources/yep.jpg',
  alt: 'Yep!',
} %}
  <img src="{{ src }}" alt="{{ alt }}">
{% endwith %}