Variables not replaced in Twig template

心已入冬 提交于 2019-12-12 02:37:58

问题


I have this PHP code (just using Twig + SwiftMailer):

# Load Twig and swiftmailer
require_once('lib/SwiftMailer/swift_required.php');
require_once('lib/Twig/Autoloader.php');
Twig_Autoloader::register();

$loader = new Twig_Loader_Filesystem('views');
$twig = new Twig_Environment($loader, array(
    'cache' => 'cache',
));

$mailer = Swift_Mailer::newInstance(Swift_MailTransport::newInstance());

# Render twig template to a string
$template = $twig->loadTemplate('email.twig');
$body = $template->renderBlock('body', array('name' => $_POST["name"], 'letter' => $_POST["letter"]));

$message = Swift_Message::newInstance()
    ->setFrom("info@mydomain.com")
    ->setSubject("Hi, ".$_POST["name"]." blahblahblah")
    ->setBody($body, 'text/html')
    ->setTo($_POST["email"]);

# Send email, using PHP mail function
$retval = $mailer->send($message);

About my email.twig template:

  • It contains {{ name }} and {{ letter }}
  • It's contained between {% block body %} ... {% endblock %}
  • It has a <style> node, with a few CSS styles.

UPDATED: Link to template here

The email is sent properly, but with 2 problems:

  • The second variable, letter, is not replaced. It's empty, even when $_POST['letter'] is not empty
  • Not all CSS styles are properly applied. I guess I can't use all the CSS properties in an email. Am I right?

Any clues?


回答1:


I had a similar problem and find a solution : that was due to some non-printable chars in the template. Not sure that it's the same for you, but maybe you should just try to rewrite the {{ letter }} part. (My french keyboard insert an invisible char with the combination of Alt-Gr + space).

Object variable don't display in a twig template



来源:https://stackoverflow.com/questions/34386253/variables-not-replaced-in-twig-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!