Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialcynnimon
4,001 PointsIs it possible to access PHP variables in Twig?
Hi, I'm trying to do the challenge presented in the video. I want to access a PHP variable from Twig. PHP code:
<?php
if ($result > 0) {//mail has been sent
$status = 'success';
$app->render('success.twig');
} else {//mail hasn't been sent
$status = 'fail';
$app->render('fail.twig');
}
?>
And I want to use it in Twig like:
{% if status == 'success' %}
{% set stat = 'success' %}
{# some more code #}
{% elseif status == 'fail' %}
{% set stat = 'fail' %}
{# some more code #}
{% endif %}
But this doesn't work. How do I access "$status"? Or should I create a status variable IN Twig?
2 Answers
Emily Peregrine
16,848 PointsI disagree with Ted. One example I can think of is if you have a user, you might need to hand their username to the template so it can display it, you also might want to know whether the user is logged in so you can show log in and log out buttons respectively.
You can pass variables using an array as the second parameter in the $app->render()
method
$app->get('/foo', function () use ($app) {
$app->render('the-template.php', array(
'name' => 'John',
'email' => '[email blocked]',
'active' => true
));
});
I take no credit for this example, I simply found it at http://help.slimframework.com/discussions/questions/4-template
The docs link on that site is outdated, here is a newer one: http://docs.slimframework.com/view/rendering/
Hope this helps!
Ted Sumner
Courses Plus Student 17,967 PointsI have not tried to do this, but I have two thoughts. I don't think that PHP will look at a .twig file. I did some quick research and found a reference that Twig is a templating language and intentionally does not support back end languages. It makes some sense. And if you look at the final index.php file from this project (below), the back end language is all in the index file. This code should be cleaned up and placed in other files to be called, but the idea is the same.
Twig implements MVC programming. That means the pages are divided into 3 parts: Model, View, Controller. The View is Twig and controls only what is displayed. The controller is Slim, which gives commands to the Model (or view). The php code is the Model. Those should all be separate. In the Slim application, I think they combine the model and view in the index.php file.
Here is the final index.php with a comment where I think the code should be moved to a different file:
<?php
// require Slim
require 'vendor/autoload.php';
// Set time zone
date_default_timezone_set('America/Los_Angeles');
//slim-views is required for Twig
//see https://github.com/slimphp/Slim-Views
//must install via composer
$app = new \Slim\Slim(array(
'view' => new \Slim\Views\Twig()
));
$view = $app->view();
$view->parserOptions = array(
'debug' => true
);
//the code below enables us to use the helpers below
//urlFor siteUrl baseUrl currentUrl
//documentation at https://github.com/slimphp/Slim-Views
$view->parserExtensions = array(
new \Slim\Views\TwigExtension(),
);
$app->get('/', function() use ($app) {
$app->render("about.twig");
})->name('home');
$app->get('/contact', function() use ($app) {
$app->render("contact.twig");
})->name('contact');
// Move this to a new file
$app->post('/contact', function() use ($app) {
$name = $app->request->post('name');
$email = $app->request->post('email');
$msg = $app->request->post('msg');
if (!empty($name) && !empty($email) && !empty($msg)) {
$cleanName = filter_var($name, FILTER_SANITIZE_STRING);
$cleanEmail = filter_var($email, FILTER_SANITIZE_EMAIL);
$cleanMsg = filter_var($msg, FILTER_SANITIZE_STRING);
} else {
//message the user there was a problem
$app->redirect('/contact');
}
$transport = Swift_SendmailTransport::newInstance('/usr/sbin/sendmail -bs');
$mailer = \Swift_Mailer::newInstance($transport);
$message = \Swift_Message::newInstance();
$message->setSubject('Email from Our Website');
$message->setFrom(array(
$cleanEmail => $cleanName
));
$message->setTo(array('teds@biblewordstudy.net'));
$message->setBody($cleanMsg);
$result = $mailer->send($message);
if ($result>0) {
// send a message that says thank you
$app->redirect('/');
} else {
// send a message to the user that the message failed to send
// log that there was an error
$app->redirect('/contact');
}
});
// End of where the code should be moved.
$app->run();
Antonio Jaramillo
15,604 PointsAntonio Jaramillo
15,604 PointsDid you ever come up with a solution to your issue? I've used jQuery as a work around solution to ensure that my users fill in all of the input fields and to disable my submit button until they do so. But I can't access values from variables set in my PHP file, nor can I give error specific messages(e.g. "Your email is invalid").