Search code examples
symfonyemailtwigswiftmailersymfony-3.2

Can't send a variable to twig in order to send an email


I want to send an confirmation email, but I can't send the variable of my form to my email

Here's my code

        if($form->isValid() && $form->isSubmitted()) {
        $NewsLetters = $form->getData();

        if(!$NewsLetters->getNom()) {
            $NewsLetters->setNom("Anonyme");
        }

        $em->persist($NewsLetters);
        $em->flush();

        $nom = $NewsLetters->getNom();

        $message = (new \Swift_Message('Confirmation d\'inscription à la newsletter'))
            ->setFrom('[email protected]')
            ->setTo($NewsLetters->getEmail())
            ->setBody(
                $this->renderView('emails/confirmationEmail.html.twig'),
                array('nom' => $nom,      //HERE
                ),
                'text/html'
            );
        $this->get('mailer')->send($message);

But twig give me this error

Variable "nom" does not exist in emails\confirmationEmail.html.twig at line 4.

<html>

<body>
Vous avez été inscrit avec succès à la Newsletter : {{ nom }}
{#{{ newsletterWebsite }} {{ newsletterStylo }} {{ newsletterCrayon }}#}
</body>
</html>

Normally it's work

Thanks for your help !


Solution

  • Seems a problem of wrong indentation: the array with params should be passed as second argument of the renderView method as follow:

     $message = (new \Swift_Message('Confirmation d\'inscription à la newsletter'))
                ->setFrom('[email protected]')
                ->setTo($NewsLetters->getEmail())
                ->setBody(
                    $this->renderView(
                      'emails/confirmationEmail.html.twig',
                       array('nom' => $nom),
                    ), // close renderView
                    'text/html'
                ); // close setBody
    

    Hope this help