doulianglou0898
2015-07-27 15:28
浏览 25
已采纳

将控制器参数传递给模板symfony2

I have a route like this: index:

path:     /{category}
defaults: { _controller: AcmeDemoBundle:Index:index, category: "default" }
requirements:
categoria: "foo|bar|this|or|that"

and the relative controller is:

<?php
namespace Acme\DemoBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class IndexController extends Controller
{
    public function indexAction($category)
    {
        $data = array("Content1", "Content2");
        return $this->render('AcmeDemoBundle:Default:index.html.twig', array('data' => $familiari));
    }
}
?>

What if I want to use the value stored in $category inside the template index.html.twig? I tried passing the variable category with the render function but I get an error! Thanks beforehand!

图片转代码服务由CSDN问答提供 功能建议

我的路线如下: index:

  路径:/ {category} 
defaults:{_ control:AcmeDemoBundle:Index:index,category:“default”} 
requirements:
categoria:“foo | bar | this |或| that”
   
 
 

并且相对控制器是:

 &lt;?php 
namespace Acme \ DemoBundle \ Controller; 
 
use Symfony \ Bundle \ FrameworkBundle \  Controller \ Controller; 
 
class IndexController扩展Controller 
 {
公共函数indexAction($ category)
 {
 $ data = array(“Content1”,“Content2”); 
返回$ this-&gt;  render('AcmeDemoBundle:默认:index.html.twig',array('data'=&gt; $ familiari)); 
} 
} 
?&gt; 
   
  
 

如果我想在模板index.html.twig中使用$ category中存储的值,该怎么办? 我尝试使用渲染函数传递变量类别,但是我收到错误! 先谢谢!

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dqpdb82600 2015-07-27 16:20
    已采纳

    The 2nd parameter of render() is an array of parameters that can be accessed in the rendered template. So if you pass $category in like this:

      public function indexAction($category)
        {
            $data = array("Content1", "Content2");
            return $this->render('AcmeDemoBundle:Default:index.html.twig', 
                  array('data' => $familiari, 'category'=>$category));
        }
    

    Then you can access it in the template using:

    {{ category }}
    
    已采纳该答案
    打赏 评论

相关推荐 更多相似问题