简体   繁体   中英

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.

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM