symfony中的render方法如何用于将数据传递给模板?

时间:2015-11-26 14:22:44

标签: php symfony model-view-controller rendering

我正在尝试学习symfony并正在阅读symfony网站上的书。我无法理解第一个示例symfony应用程序部分中的代码的以下部分。 BlogController返回$this->render('Blog/list.html.php',array('posts'=>$posts));} 那么如何在视图模板中访问array('posts=>$posts')

// 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>

1 个答案:

答案 0 :(得分:1)

它的作用是使用extract然后使用包含。类似的东西:

<?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();
}

您可以在Symfony Templating Component中看到真实的实现。