13

I am trying to trigger a mail to customer after they place an order. This email will carry all the cross sell products of the products ordered.

I used the following links as reference:

send email using event observer

Advanced Transactional Email Templates

All is working well.

But now my doubt is, will I be able to use foreach loop inside the html file put inside the locale directory?

So that I could iterate and print all the product info in the mail template. Can anyone help?

2 Answers 2

22

I think that it is not possible to directly perform a foreach loop in emails, but what you could do is include a block that will do the loop in a regular template.

In you email add something like the following.

{{block type='core/template' area='frontend' template='email/template.phtml' items=$items}}

Then in your template add the following.

<?php foreach ($this->getItems() as $_item): ?>
    <p><?php echo $_item['name'] ?></p>
<?php endforeach; ?>

For more information I followed this blog

3
  • Ya I am actually was trying this. will accept this in 2 mins
    – Shathish
    Commented Sep 27, 2013 at 6:27
  • Do we have to add this block inside email template? And will it understand items=$items? As $items is php variable.
    – AkshayT
    Commented Aug 21, 2015 at 12:10
  • Hi, I tried above not working for me. Any suggestions
    – AkshayT
    Commented Aug 23, 2015 at 19:21
4

Actually you can use a for loop in emails. I've tested it on 2.3.3 version. This is the code location to inspect. This is how it looks like in the template:

<ul>
  {{for item in data.items}}
     <li>Name: {{var item.name}}</li>
  {{/for}}
</ul>

The transport information:

$this->transportBuilder->setTemplateVars(
[
 'items' => [
              ['name' => 'Product1'],
              ['name' => 'Product2']
            ]
...

Aside. In 2.3.4 the code was refactored, but I believe it still should work as it was not removed. Please remember that Magento removed the ability to call functions on objects as of this version, so your order->getItems() function may not work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.