Ahmad Yousef
Ahmad Yousef

Reputation: 659

how to access returned value by twig - silex

I'm new in silex and twig. I want to access a returned value from a function and put it in my twig template. This is my code :

namespace classes;

use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
$blogPosts = array(
1 => array(
    'date'      => '2011-03-29',
    'author'    => 'igorw',
    'title'     => 'Using Silex',
    'body'      => '...',
),
);
class GlobalController
{
public function indexAction(Application $app, Request $request)
{

    $output = '';
    foreach ($blogPosts as $post) {
        $output .= $post['title'];
        $output .= '<br />';
    }

  return $output;
      }
    }

I want to access $output and show it in my template. Can I do that? because I have other similar functions and they are retrieving data from database and returning them as values, I want to include these values in the template .. Is that possible ?

I tried these but they didn't work :

{{ GlobalController.output }}
{# Or #}
{{ GlobalController.indexAction.output }}

Update : I added this in my routing:

$app->get('/news/', function () use ($app) {
return $app['twig']->render('news.php.twig', array(
'output' => $output,
));
});

and it gave me Undefined variable: output notice.

Thank you

Upvotes: 1

Views: 643

Answers (1)

Andrius
Andrius

Reputation: 5939

When you're finishing up with your route, you need to show which twig template you're using and include all the variables that you want to use in twig:

return $app['twig']->render('some_template.twig', array(
    'output' => $output,
));

Now you can access the variable with {{ output }}

Upvotes: 0

Related Questions