Kent Bjerg Budolfsen Kent Bjerg Budolfsen - 5 days ago 4x
Twig Question

Twig template data swiftmailer

Just set up an slim 3 application with twig and swiftmailer.

I made a MailController to fetch the emailaddress and name from a customers table - it works great and swiftmailer send an email to the right address - using the twig-template I created - but the problem is that it doesn't fetch the data that I have setup in twig.

The code for my controller is here


namespace Cart\Controllers;

use Slim\Router;
use Slim\Views\Twig;
use Cart\Models\Order;
use Cart\Models\Product;
use Cart\Models\Address;
use Cart\Models\Delivery;
use Cart\Models\Customer;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;

* @return MailController
class MailController
protected $transport;
protected $mailer;
private $view;

public function __construct(Twig $view)
$this->view = $view;

// Create Transport
$https['ssl']['verify_peer'] = FALSE;
$https['ssl']['verify_peer_name'] = FALSE;

$this->transport = \Swift_SmtpTransport::newInstance('', 587, 'tls')
// Create Mailer with our Transport.
$this->mailer = \Swift_Mailer::newInstance($this->transport);


public function mailLisbeth($hash)

// // Here I'm fetching my email template from my template directory.
$welcomeEmail = $this->view->fetch('mail/order.twig');

$mailorder = Order::with('customer', 'address', 'products' )->where('hash', $hash)->first();

// Setting all needed info and passing in my email template.
$message = \Swift_Message::newInstance('Ordre fra Webshop')
->setFrom(array('' => 'Kent'))
$mailorder->customer->email => $mailorder->customer->name,
// Send the message
$results = $this->mailer->send($message);

And my twig template her

<div class="row">
<div class="col-md-12">
<h3>Order #{{ }}TEST</h3>
<div class="row">
<div class="col-md-6">
{{ }}<br>
{{ }}<br>
{{ mailorder.address.address1 }}<br>
{{ mailorder.address.address2 }}<br>
{{ }}<br>
{{ mailorder.address.postal_code }}<br>
{{ }}<br>
{{ }}<br>
{{ }}<br>

<div class="col-md-6"></div>
{% for product in customer.products %}
<a href="{{ path_for('product.get', {slug: product.ID })}}">{{ product.Navn }}</a> ( x {{ product.pivot.quantity}})<br>
{% endfor %}
Levering: DKK 150,00 <br>
<strong>Order total: DKK {{ | number_format(2,',','.')}}</strong>

The problem could lie in a missing passing of the mailorder variable to the twig template - but since I have used the same config and variable in another page - I can't figure out why it doesn't get into the twig template.

Hope someone has a clue... Thanks


As far as I can see, you are not rendering your template. Instead you just pass the twig file to swiftmailer.

I am not sure how it works exactly in slim but you probably have to do something like

$twig->render($welcomeEmail, ['mailorder' => $mailorder]);

Then pass the result to swiftmailer.