MWA MWA - 1 month ago 12
PHP Question

Loop through twig array in Drupal

I'm having trouble looping through what I'm hoping is a simple data array in an html.twig file in Drupal 8. When I add the below block to a page, Drupal encounters an "unexpected error". And for now it's okay that this is static to the page.

Note: I'm less than a week into Drupal and twig and my PHP is 10 years rusty.

{%

set top_customers = {
{ name: "Altera G", logo: "logo-alterg.png", }
{ name: "Hollywood Was Museum", logo: "logo-hollywoodwaxmuseum.png", }
{ name: "iroaHealth", logo: "logo-iorahealth.png", }
{ name: "Lionel", logo: "logo-lionel.png", }
{ name: "Mashable", logo: "logo-mashable.png", }
{ name: "People Fluent", logo: "logo-peoplefluent.png", }
{ name: "Shop Kick", logo: "logo-shopkick.png", }
{ name: "Wistia", logo: "logo-wistia.png", }
}

%}

{{ dump(top_customers) }}

<section class="row cta-section row-padding-130">
<div class="row-inner site-width">
<div class="brick-10 center-brick">
<h3>These brands are changing the way they think about AP by using MineralTree</h3>
</div>
<div class="brick-12 center-brick">
<ul class="logo-list margin-top-78 clearfix">
{% for customer in top_customers %}
<li>
<img class="customer-logo img-fluid" src="{{ directory }}/images/customer-logos/{{ customer.logo }}" alt="{{ customer.name }}" />
</li>
{% endfor %}
</ul>
</div>
<div class="brick-6 center-brick">
<div class="margin-top-78">
<a href="/about-us/our-customers.html" class="solid-cta-btn button-large">view all our customers</a>
</div>
</div>
</div>
</section>


Thanks for your help!

Answer

Try defining top_customers as array as follow:

{%

set top_customers = [
   { name: "Altera G", logo: "logo-alterg.png" },
   { name: "Hollywood Was Museum", logo: "logo-hollywoodwaxmuseum.png", },
   { name: "iroaHealth", logo: "logo-iorahealth.png", },
   { name: "Lionel", logo: "logo-lionel.png", },
   { name: "Mashable", logo: "logo-mashable.png", },
   { name: "People Fluent", logo: "logo-peoplefluent.png", },
   { name: "Shop Kick", logo: "logo-shopkick.png", },
   { name: "Wistia", logo: "logo-wistia.png", },
 ]

 %} 

Here a working example