SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH
email template

How to add foreach loop in email template magento 2?

In Magento, the implementation of the loop in an email template has many disadvantages. When I first started getting used to email templates in Magento I spent a lot of time doing loops with lots of data. And how to do the transmission of that data to the .phtml file to perform its tasks. Here, I will show you a simple way to pass and send data from the email template to the .phtml file and use them .

You can read related articles on creating a simple email sent here

for example, in the controller file, the data transfer has the form

->setTemplateVars([
'items' => $post['items'],
])

so in the email template file will have the form

<!--@subject Email Product  @-->

{{template config_path="design/email/header_template"}}

<table>
     {{layout handle="email_order_items_product" items=$items  area="frontend"}}
 <!--@styles
    table table table tbody tr td {text-align: center;border: 1px solid #ccc;padding: 5px 0;}
 @-->
</table>
{{template config_path="design/email/footer_template"}}

You can add style using <!–@styles @–> . In directory layout module or theme you can add email_order_items_product called in the handle email template layout/email_order_items_product.xml

<?xml version="1.0"?>
<page  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <block class="Magento\Framework\View\Element\Template" name="customemail_index_emailsend" template="Magepow_Customemail::email.phtml"/>
    </body>
</page>

in file email.phtml

<?php 
$_items = $block->getItems();
?>
<tbody>
	<?php foreach ($_items as $value): ?>
		<?php 
				echo "<tr>";
			        echo "<td>" . $value . "</td>";
		        echo "</tr>";
		?>
	<?php endforeach; ?>
</tbody>