如何在视图中访问模型 - Symfony 2


How to get access to the model in the view - Symfony 2

我有以下模型:

class Person
{
    public $name;
    function __Construct( $name )
    {
        $this->name = $name;
    }
}

我有以下控制器:

class NavigationController extends Controller
{
    public function indexAction()
    {
        $people = array(
            new Person("James"),
            new Person("Bob")
        );
        return $this->render('FrameworkBundle:Navigation:index.html.php', $people);
    }
}

如何访问视图中的模型数组。有没有办法直接访问模型,或者我必须分配这样的属性:?

class NavigationController extends Controller
{
    public function indexAction()
    {
        $people = array(
            new Person("James"),
            new Person("Bob")
        );
        return $this->render('FrameworkBundle:Navigation:index.html.php', array( "model" => $people ) );
    }
}

视图:

<?php 
    foreach( $model as $person )
    {
       echo $person->title;
    }
?>

上述问题在于用户可以将其更改为

return $this->render( 'FrameworkBundle:Navigation:index.html.php', array( "marybloomingpoppin" => $people ) );

使用您使用的示例视图,您已经有了正确的实现:

class NavigationController extends Controller
{
    public function indexAction()
    {
        $people = array(
            new Person("James"),
            new Person("Bob")
        );
        return $this->render('FrameworkBundle:Navigation:index.html.php', array( "model" => $people ) );
    }
}

提到了有人可能会更改控制器中的赋值的担忧,但如果有人仅在一个地方而不是所有地方更改变量的名称,您总是会这样做。所以我不认为这是一个问题。