如何将getResult对象传递给Twig?

时间:2017-09-15 13:13:05

标签: php symfony twig

简单代码:

/**
  * @Route("/search")
  */
    public function searchAction(Request $request) {
    $repository = $this->getDoctrine()->getRepository(Bike::class);

    $query = $repository->createQueryBuilder('b')
        ->where('b.brand >= :id')
        ->setParameter('id', '1')
        ->getQuery();

    $result = $query->getResult());

我试过

echo $result[0]['id'];

将数据保存到变量但它给出:

Cannot use object of type AppBundle\Entity\Bike as array

var_dump($result[0]);

我有一些多维数组

object(AppBundle\Entity\Bike)[589]
  private 'id' => int 1
  private 'model' => string 'XXX' (length=9)
  private 'material' => string 'BBB' (length=6)

我想将这个数组或变量从数组传递给 template.twig

2 个答案:

答案 0 :(得分:0)

您真的需要阅读symfony documentation

你会找到解决方案,如下所示:

$this->render('default/index.html.twig', array(
'variable_name' => 'variable_value',
));

答案 1 :(得分:0)

    public function searchAction() {
    $em = $this->getDoctrine()->getManager();
    $bike = $em->getRepository("NameOfYourBundle:Bike")->findAll();

    return $this->render('NameOfYourBundle:ForderName:nameOfTheView.html.twig', array('bike'=>$bike));
}

现在在你看来:

{% for b in bike %}
    {% if b.id >= 1 %}
        // now put the names of attribs you need
    {% endif %}
{% endfor %}

我希望这会对你有所帮助。