问题
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