Looping over assoc array in template

<%- if @topic_view.topic.tags.present? %>
<%= t 'js.tagging.tags' %>: <%- @topic_view.topic.tags.each do |t| %> <%= t %> <%- end %>
<% end %>

Silverstripe Version: 4.6

How do I get this associative array in my template and loop over the keys and values?

$postData = array('name' => 'Foo', 'Message' => 'This is my message');

$email = SilverStripe\Control\Email\Email::create()
    ->setHTMLTemplate('Email\\MyCustomEmail') 
    ->setData([
        'UserInput' => $postData
    ])
    ->setFrom($from)
    ->setTo($to)
    ->setSubject($subject);

if ($email->send()) {
    //email sent successfully
} else {
    // there may have been 1 or more failures
}

Now in my email template I’d like to loop over all user input which is in $postData

<% loop $input %> $Me.Value <% end_loop %>

But this just doesn’t work. Looking for a fix :slight_smile:

It depends a lot on the end result you want. You can just pass an array into the ->setData() method and access its contents directly:

->setData($postData)

and in your template:

<p>Name: $name</p>
<p>Message: $Message</p>

If you really need to loop through all the elements in the array, then you’d probably need to convert it into an ArrayList by looping it in PHP and pushing the keys / values:

$data = ArrayList::create();

foreach ($postData as $key => $value) {
  $data->push(ArrayData::create([
    'Key' => $key,
    'Value' => $value
  ]);
}

//....

->setData(['UserInput' => $data])

Then the template becomes:

<% loop $UserInput %>
  <p>$Key = $Value</p>
<% end_loop %>

*all entirely untested, and possibly wrong :wink: