1

Using drupal 8.7.x

I have an associative array that is returned to twig. However I can't seem to get the data displayed.

Associative array:

array_push($mealsArray, ["meal" =>
  [
    ['strMeal' => $mealTitle],
    ['strMealThumb' => $mealImage],
    ['mealUrl' => $mealTitleUrl]
  ]
]);

Return to twig:

return [
  '#theme' => 'recipe_search_block',
  '#meals' => $meals,
  '#ingredientList' => $ingredients,
  'form' => $form,
];

In twig I'm trying to display them like this:

   <div class="u-row u-margin-top">
    {% for meal in meals %}
      {% for fields in meal %}
        <div class="u-col-md-3 u-col-xs-6">
          <div class="m-recipe">
            <a class="m-recipe__link"href="/recipes/{{ fields["mealUrl"] }}"></a>
            <header class="m-recipe__header u-margin-bottom">
              <h3>{{ fields["strMeal"] }}</h3>
            </header>
            <div class="m-recipe__image">
              <img src="{{ fields["strMealThumb"] }}" alt="{{ fields["strMeal"] }}">
            </div>
          </div>
        </div>
      {% endfor %}
    {% endfor %}
  </div>

When I debug with kint this is the output I get Kint output

Any help would be appreciated, thanks in advance!

  • Hi, Are strMeal and strMealThumb both part of the same meal – user3127648 Jul 18 at 19:13
  • According to your kint output it's probably fields.meal.strMeal, and so on – Clive Jul 18 at 19:48
  • @Clive I tried that and it doens't seem to work. – Geordi Feijens Jul 19 at 7:59
  • @user3127648 Yes, they are both part of the same meal. – Geordi Feijens Jul 19 at 8:00
1

Sollution:

Associative array:

array_push($mealsArray, ["meal" =>
  [
    'strMeal' => $mealTitle,
    'strMealThumb' => $mealImage,
    'mealUrl' => $mealTitleUrl
  ]
]);

Twig:

{% for meal in meals %}
      {% for fields in meal %}
        <div class="u-col-md-3 u-col-xs-6">
          <div class="m-recipe">
            <a class="m-recipe__link" href="/recipes/{{ fields.mealUrl }}"></a>
            <header class="m-recipe__header u-margin-bottom">
              <h3>{{ fields.strMeal }}</h3>
            </header>
            <div class="m-recipe__image">
              <img src="{{ fields.strMealThumb }}" alt="{{ fields.strMeal }}">
            </div>
          </div>
        </div>
        {% endfor %}
    {% endfor %}

The return statement remains unchanged.

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.