How can i access repository functions in twig temp

2019-04-05 10:11发布

I have the class categroies and class Products.

In my repository i have function

getProducts($categoryid,$location)

I need to loop in twig template like this

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

or is there any better way for that

4条回答
smile是对你的礼貌
2楼-- · 2019-04-05 10:26

The solution is the other way around as how this is done right now. The Category entity should have a one-to-many relation. Take a look at http://symfony.com/doc/2.0/book/doctrine.html#entity-relationships-associations

The category Entity should then have an EntityCollection attribute called 'products'. In your template you then can solve this in the following way:

{% for category in categories %}
    --{{ category.name }}--
      {% for product in category.products %}
     --{{ product.name }}--
    {% endfor %}
 {% endfor %}
查看更多
该账号已被封号
3楼-- · 2019-04-05 10:27

I suspect that all you really need is a left join using a WITH expression. Something like:

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));

That will give you all the categories with their respective products for a given location.

查看更多
爷的心禁止访问
4楼-- · 2019-04-05 10:32

You shouldn't. Thats business logic, that should not appear in templates. One solution is to create a new action within a controller and in your template call

{% render '@MyBundle:Product:list' with {category: category.id} %}
查看更多
We Are One
5楼-- · 2019-04-05 10:36

It's a pretty old question, but I'm missing a really simple solution like this one.

It is possible to pass the repo object to twig and call the repo public methods from twig like so:

In your controller

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

And then in your twig template :

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

Im saying it's possible, many would argue that templates should only display data and let controllers gather the data. I personally don't mind letting my templates getting their data themselves.

查看更多
登录 后发表回答