Twig direct include doesn't work, only "with"ing specific keys does

558 views Asked by At

I'm using Pattern Lab with twig templates and having an issue with using objects directly in the with statement in includes.

This is my teaser-content-blocks organism:

{% set content_blocks = [
  {
    teaser_photo: {
      url: 'https://img.buzzfeed.com/buzzfeed-static/static/enhanced/terminal01/2011/3/29/17/enhanced-buzz-14894-1301433714-5.jpg',
      alt: 'Man sleeping on a cake',
      title: 'Man sleeping on a cake',
      height: '200px',
      width: '400px',
    },
  }
] %}

<div class="teaser-content-blocks">
  {% for content_block in content_blocks %}
    {% include '@molecules/teaser-content-block.twig' with content_block only %}
  {% endfor %}
</div>

This is the teaser-photo atom:

<div class="teaser-photo">
  <img
    src="{{ url }}"
    alt="{{ alt }}"
    title="{{ title }}"
  />
</div>

And this is what I'm attempting to do with the teaser-content-block molecule:

<div class="teaser-content-block">
  <div class="left">
    {% include '@atoms/teaser-photo.twig' with teaser_photo only %}
  </div>
  <div class="right">
    {% include '@atoms/title.twig' with { title: 'Sleep on a cake', element: 'h3' } only %}
    {% include '@atoms/teaser-body.twig' with { body: "When we say 'sweet dreams', this isn't quite what we mean! Check this mad lad not understanding the general concept of pillows! This utter banterboy has completely confused what he is meant to use as a confectionary-based celebration of one's birth and a soft item of bedding designed to cushion the head during sleep or light rest. Mental!" } only %}
  </div>
</div>

It seems, however, that the with teaser_photo only statement causes twig to break and not compile, with an error of Catchable fatal error: Argument 1 passed to Twig_Template::display() must be of the type array, null given.

If I change that include statement to the following:

{% include '@atoms/teaser-photo.twig' with { url: teaser_photo.url, alt: teaser_photo.alt, title: teaser_photo.title } only %}

... it works fine, but this is way too verbose for my liking. I'd rather just pass the object down as it is. It just seems to not want to pick it up in the correct manner, even though theoretically it should work the same.

I'm not a twig expert so I may be missing something really obvious.

Any help much appreciated as always!

1

There are 1 answers

0
Matt Fletcher On

Discovered the issue. Pattern Lab of course tries to render every available pattern, so it was trying to render teaser-content-block.twig which is trying to reference the variable teaser_photo, which of course doesn't exist in this scope. So the cure was to replace that line with one that uses a default, like so:

{% include '@atoms/teaser-photo.twig' with teaser_photo|default({}) only %}

... or at least something that does a similar thing. Thanks to @DarkBee too for taking the time to have a look.