forech with sql in twig symfony2

时间:2012-11-15 18:44:25

标签: php symfony twig

我在PHP中有以下代码:

$em     = $this->getDoctrine()->getManager(); 
$entity = $em->getRepository('DataBundle:SomeData')->findAll();

foreach ($entity as $item)
{
   echo $item->getSomething();

   $data = $em->getRepository('DataBundle:SomeData')
              ->findBySomeId($item->getSomeId());

   foreach ($data as $somevar)
   {
      echo $somevar->getSomeOtherData();   
   }
}

可以在Twig中翻译吗?如果是这样,我会很感激如何做到这一点。

由于

2 个答案:

答案 0 :(得分:1)

您需要在模型中进行实体计算,由控制器启动并将这些对象传递到View中,然后将其推送到模板引擎中。

Twig看起来像这样:

{% for item in entity %}
  {{ item.getSomething }}

  {% for somevar in data %}
     {{ somevar.getSomeOtherData }}
  {% endfor %}
{% endfor %}

编辑:这是一个更精确的答案,你可以从这里推断出来:

// Controller
public function demoAction()
{
    $demoModel = $this->get('demo.bundle.model.demo');
    $demoView = $this->get('demo.bundle.view.demo');
    $demoResult = $demoModel->myModelCalculation();

    return $demoView->myDemoView($demoResult);
}

//Model
public function myModelCalculation()
{
    return $this->getRepository('DataBundle:SomeData')->findAll();
}

//View
public function myDemoView($entity)
{
    return $this->getTemplatingEngine()->renderResponse('DemoBundle:demo:index.html.twig', array('entity' => $entity));
}

//Twig
{% for item in entity %}
    {{ item.getSomething }}
{% endfor %}

Symfony2很容易学习,我建议你做他们的教程和阅读文档。 http://symfony.com/doc/current/index.html

答案 1 :(得分:0)

//SomeData.php
// ....
class SomeData 
{
  // ...

  /**
   * @ORM\OneToMany(targetEntity="SomeData")
   */
  private $children;
}


//Controler
class SomeController
{
  /**
   * @Template()
   */
  public function someAction()
  {
    return ('entities' => $this->getDoctrine()->getRepository('DataBundle:SomeData')->findAll());
  }
}

//some.html.twig
{% for item in entities %}
   {{ item.getSomething }}

   {% for somevar in item.children %}
      {{ somevar.getSomeOtherData }}
   {% endfor %}
{% endfor %}