level0
level0

Reputation: 343

How is render method in symfony used to pass the data to template?

I am trying to learn symfony and was reading through The book which is on symfony site.I cannot understand the following part of the code in the section first Sample symfony application . The BlogController returns $this->render('Blog/list.html.php',array('posts'=>$posts));} so how is array('posts=>$posts') accessed in the view template

// src/AppBundle/Controller/BlogController.php
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller ;

class BlogController extends Controller
{
 public function listAction()
 { $posts = $this->get('doctrine')->getManager()->createQuery('SELECT p FROM AcmeBlogBundle:Post p')->execute();
return $this->render('Blog/list.html.php',array('posts'=>$posts));
}



<!-- app/Resources/views/Blog/list.html.php -->
<?php $view->extend('layout.html.php')?>
<?php $view['slots']->set('title','List of Posts')?>
<h1>
List of Posts
</h1>
<ul>
<?php foreach($posts as $post):?>
<li>
<a href="<?phpecho $view['router']->generate('blog_show',array('id'=>$post->getId()))?>">
<?php echo $post->getTitle()?>
</a>
</li>
<?php endforeach?>
</ul>

Upvotes: 0

Views: 603

Answers (1)

joksnet
joksnet

Reputation: 2325

What it does is use extract and then an include. Something like:

<?php
function render($template, array $vars) {
  extract($vars);
  ob_start(); // This is for retrieving the result
              // of the template and not print it directly.
  include $template;
  $result = ob_get_clean();
}

You can see the real implementation in Symfony Templating Component.

Upvotes: 1

Related Questions