如何在symfony2中的twig模板中访问存储库函数

时间:2012-08-01 06:58:35

标签: php symfony doctrine-orm twig

我有class categroiesclass Products

在我的存储库中我有功能

getProducts($categoryid,$location)

我需要循环使用这样的树枝模板

 {% for category in categories %}
    --{{ category.name }}--
      {% for product in getProducts(category.id,location) %}
     --{{ product.name }}--
    {% endfor %}
 {% endfor %}

还是有更好的方法

4 个答案:

答案 0 :(得分:18)

你不应该。这是业务逻辑,不应该出现在模板中。一种解决方案是在控制器和模板调用中创建新操作

{% render '@MyBundle:Product:list' with {category: category.id} %}

答案 1 :(得分:6)

这是一个非常古老的问题,但我错过了一个非常简单的解决方案。

可以将repo对象传递给twig并从twig中调用repo public方法,如下所示:

在您的控制器中

$oCatRepo = $this->getDoctrine()->getManager()->getRepository('AppBundle:Categories');
....
return $this->render('product_list.html.twig', array('oCatRepo' => $oCatRepo));

然后在你的树枝模板中:

{{ oCatRepo.getProducts(category.id, location) }}

我说这是可能的,许多人会争辩说模板应该只显示数据并让控制器收集数据。我个人不介意让我的模板自己获取数据。

答案 2 :(得分:1)

我怀疑你真正需要的是使用WITH表达式的左连接。类似的东西:

class CategoryManager
{
    public function loadCategoriesProductsForLocation($location)
    {
        $qb = $this->em->->createQueryBuilder();

        $qb->addSelect('category');
        $qb->addSelect('product');

        $qb->from('MyBundleBundle:Category','category');

        $qb->leftJoin('category.products','product', 
            Expr\Join::WITH, $qb->expr()->eq('product.location', $location));

这将为您提供针对特定位置的所有类别及其各自的产品。

答案 3 :(得分:1)

解决方案是另一种方式,就像现在这样做。 Category实体应具有一对多关系。看看http://symfony.com/doc/2.0/book/doctrine.html#entity-relationships-associations

类别实体应该具有名为“products”的EntityCollection属性。在您的模板中,您可以通过以下方式解决此问题:

{% for category in categories %}
    --{{ category.name }}--
      {% for product in category.products %}
     --{{ product.name }}--
    {% endfor %}
 {% endfor %}
相关问题