TheKid
TheKid

Reputation: 11

twig how to render a twig template as a variable

I'm trying to render twig template as variable, using symfony. I have a 'sendAction' Controller, which uses the mailgun API to send emails to one or more mailing lists. Here is my code for the Controller:

public function sendAction(Request $request, Newsletter $newsletter, MailgunManager $mailgunManager) {
  $form = $this->createForm(SendForm::class);
  $form->handleRequest($request);

  $formData = array();

  if ($form->isSubmitted() && $form->isValid()) {

        $formData = $form->getData();

        $mailingLists = $formData['mailingLists'];

        foreach ($mailingLists as $list) {

            $mailgunManager->sendMail($list->getAddress(), $newsletter->getSubject(), 'test', $newsletter->getHtmlContent());

            return $this->render('webapp/newsletter/sent.html.twig');
        }
    }
    return $this->render('webapp/newsletter/send.html.twig', array(
        'newsletter' => $newsletter,
        'form' => $form->createView()
    ));
  }
}

And here's my sendMail (mailgun) function:

  public function sendMail($mailingList, $subject, $textBody, $htmlBody) {

   $mgClient = new Mailgun($this::APIKEY);

   # Make the call to the client.
         $mgClient->sendMessage($this::DOMAIN, array(
            'from'      => $this::SENDER,
            'to'        => $mailingList,
            'subject'   => $subject,
            'text'      => $textBody,
            'html'      => $htmlBody
        ));
  }

I want my ' $newsletter->getHtmlContent()' to render template called 'newsletter.twig.html'. can anyone help me or point me in the right direction as to what I can do or Where I can find Tutorials or notes on what I am trying to do. the symfony documentation is quite vague.

Upvotes: 1

Views: 3705

Answers (2)

lxg
lxg

Reputation: 13107

Simply inject an instance of Symfony\Bundle\FrameworkBundle\Templating\EngineInterface into your action, and you’ll be able to use Twig directly:

public function sendAction(Request $request, EngineInterface $tplEngine, Newsletter $newsletter, MailgunManager $mailgunManager)
{
    // ... other code
    $html = $tplEngine->render('webapp/newsletter/send.html.twig', [
        'newsletter' => $newsletter,
        'form' => $form->createView()
    ]);
}

Note that $this->render() (in the controller action) will return an instance of Symfony\Component\HttpFoundation\Response, while $tplEngine->render() returns a HTML string.

Upvotes: 1

Sujit Agarwal
Sujit Agarwal

Reputation: 12508

You can use getContent() chained to your render function.

return $this->render('webapp/newsletter/send.html.twig', array(
        'newsletter' => $newsletter,
        'form' => $form->createView()
    ))->getContent();

Upvotes: 2

Related Questions