@Template
当前 Symfony 应用不再建议使用此扩展包。此扩展包提供的所有注解现在都已作为 PHP 属性内置在 Symfony 中。查看 Symfony 属性完整列表。
用法
@Template
注解将控制器与模板名称关联起来
1 2 3 4 5 6 7 8 9 10 11 12
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
/**
* @Template("@SensioBlog/post/show.html.twig")
*/
public function show($id)
{
// get the Post
$post = ...;
return array('post' => $post);
}
当使用 @Template
注解时,控制器应返回要传递给视图的参数数组,而不是 Response
对象。
注意
如果你想流式传输模板,你可以使用以下配置进行设置
1 2 3 4 5 6 7
/**
* @Template(isStreamable=true)
*/
public function show($id)
{
// ...
}
提示
如果 action 返回 Response
对象,则 @Template
注解将被忽略。
如果模板以控制器和 action 名称命名,就像上面的例子那样,你甚至可以省略注解值
1 2 3 4 5 6 7 8 9 10
/**
* @Template
*/
public function show($id)
{
// get the Post
$post = ...;
return array('post' => $post);
}
提示
子命名空间会转换为下划线。Sensio\BlogBundle\Controller\UserProfileController::showDetails()
action 将解析为 @SensioBlog/user_profile/show_details.html.twig
如果传递给模板的唯一参数是方法参数,你可以使用 vars
属性而不是返回数组。这与 @ParamConverter
注解 结合使用非常有用
1 2 3 4 5 6 7
/**
* @ParamConverter("post", class="SensioBlogBundle:Post")
* @Template("@SensioBlog/post/show.html.twig", vars={"post"})
*/
public function show(Post $post)
{
}
由于约定,这相当于以下配置
1 2 3 4 5 6
/**
* @Template(vars={"post"})
*/
public function show(Post $post)
{
}
你可以使其更简洁,如果方法返回 null
且未定义 vars
属性,则所有方法参数都会自动传递给模板
1 2 3 4 5 6
/**
* @Template
*/
public function show(Post $post)
{
}
本作品,包括代码示例,根据 Creative Commons BY-SA 3.0 许可协议获得许可。