2014-10-29 2 views
0

im пытается разделить мои товары по категориям с помощью javascript и twig, поэтому после того, как я привел все продукты из базы данных, я не знаю, как я могу отделять продукты с помощью {% for%}. это мой прутик код:Как я могу делить предметы по категориям с twig

<div class="col-sm-4" itemscope itemtype="http://schema.org/Product"> 
    <div class="panel panel-default"> 
     <div class="panel-heading"> 
      <h5 class="panel-title truncate">Categoria:{{ producto.idCategoria }}</h5> 
     </div> 
     <div class="panel-body"> 
      Nombre:{{ producto.producto }} 
      <img src="{{ asset('bundles/savainventario/images/'~producto.filePersistencePath) }}" 
       alt="404 file not found" class="img-thumbnail"/> 
     </div> 
     <div class="panel-footer"> 

      <div class="container-fluid"> 

       {#Precio#} 
       <span itemprop="price"> 
       Precio:{{ producto.precio }}.Bsf 
       </span> 
       {#Form#} 
       <form class="form-inline" role="form" method="get" 
         action={{ path('sava_inventario_addcart', {'id': producto.idProducto }) }}> 
        <div class="form-group"> 
         <input class="btn btn-default" type="submit" value="Agregar"> 
        </div> 

        {#Ver mas#} 
        <!-- Button trigger modal --> 
       </form> 
       <button class="btn btn-primary btn-sm" data-toggle="modal" 
         data-target="#myModal{{ producto.idProducto }}"> 
        Ver mas... 
       </button> 
       <!-- Modal --> 
       <div class="modal fade" id="myModal{{ producto.idProducto }}" tabindex="-1" role="dialog" 
        aria-labelledby="myModalLabel" aria-hidden="true"> 
        <div class="modal-dialog"> 
         <div class="modal-content"> 
          <div class="modal-header"> 
           <button type="button" class="close" data-dismiss="modal"><span 
              aria-hidden="true">&times;</span><span class="sr-only">Close</span> 
           </button> 
           <h4 class="modal-title" id="myModalLabel">{{ producto.producto }}</h4> 
          </div> 
          <div class="modal-body"> 
           <!-- Datos productos --> 
           <table class="table table-striped"> 
            <tr> 
             <td>Nombre:</td> 
             <td>{{ producto.producto }}</td> 
            </tr> 
            <tr> 
             <td>Image:</td> 
             <td> 
              <img src="{{ asset('bundles/savainventario/images/'~producto.filePersistencePath) }}" 
               alt="404 file not found"/></td> 
            </tr> 
            <tr> 
             <td>Descripcion</td> 
             <td>{{ producto.descripcionProducto }}</td> 
            </tr> 
            <tr> 
             <td>Precio:</td> 
             <td>{{ producto.precio }}</td> 
            </tr> 
            <tr> 
             <td>Cantidad:</td> 
             <td>{{ producto.cantidad }}</td> 
            </tr> 
            <tr> 
             <td>Categoria:</td> 
             <td>{{ producto.idCategoria.categoria }}</td> 
            </tr> 
            <tr> 
             <td>Modelo:</td> 
             <td>{{ producto.idModelo.modelo }}</td> 
            </tr> 
            <tr> 
             <td>Video:</td> 
             <td> 
              <iframe width="433" height="315" 
                src="//www.youtube.com/embed/tQShyqnRx3s?list=PLw4rBoBPv1Vbq16M4SFkJPZj08FMaaR-8" 
                frameborder="0" allowfullscreen></iframe> 
             </td> 
            </tr> 
           </table> 
          </div> 
          <div class="modal-footer"> 
           <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> 
          </div> 
         </div> 
        </div> 
       </div> 
      </div> 


     </div> {#footer end#} 
    </div> 
</div> 

{% endif %} 

{% endfor %} 

</div> 
</div> 

мой вопрос, как я могу разделить мои вещи по категориям, в одной категории я напечатать его в одном сНу контейнера, в другом сНу контейнер я добавлять товары из другой категории и так далее.

+0

Посмотрите алгоритм прерывания контроля. Вот пример в C - http://pastebin.com/sArUmwRa – dmnptr

+0

, который нельзя разбить на петли в twig http://twig.sensiolabs.org/doc/tags/for.html. – 2one2

+0

Зачем вам это нужно? – dmnptr

ответ

0

Если entites настроены должным образом это не должно быть трудно:

//Contoller 

/** 
* @Template() 
*/ 
public function showProductsByCategory() 
{ 
    $categories = $this->getDoctrine()->getManager() 
     ->getRepository("NamespacedBundle:Category")->findAll(); 
    return array(
     'categories' => $categories 
    ); 
} 

Предполагая, что ваши категории знают о продуктах

//Category Entity 
/** 
* @ORM\OneToMany(targetEntity="Product", mappedBy="category") 
*/ 
protected $products; 

И ваши продукты привязаны к категории

//Product Entity 
/** 
* @ORM\ManyToOne(targetEntity="Category", inversedBy="products") 
* @ORM\JoinColumn(name="category", referencedColumnName="category_id") 
*/ 
protected $category; 

Тогда ваша веточка может быть чем-то основанным на:

//Sample Twig 
{% for category in categories %} 
    <div class="container"> 
     <h1>{{category.name}}</h1> 
     <ul> 
     {% for product in category.products %} 
      <li>{{product.name}}</li> 
     {% endfor %} 
    </div> 
{% endfor %} 
+0

, поскольку я использовал elasticsearch, а не доктрину, я не могу использовать этот метод, все же дал мне представление о том, как его решить. спасибо за Ваш ответ. – 2one2

Смежные вопросы