Advertisement
  1. Code
  2. Magento

Desarrollo del Tema de Magento: Página de Categoría, Parte 1

Scroll to top
Read Time: 15 min
This post is part of a series called Magento Theme Development.
Magento Theme Development: Home Page Styling
Magento Theme Development: Category Page, Part 2

Spanish (Español) translation by Elías Nicolás (you can also view the original English article)

Felicidades por completar la página principal de su nuevo tema y comenzar con la siguiente página. En este tutorial, comenzaremos a modificar la página de categorías de nuestro tema de Magento.

La página de categorías consta esencialmente de cuatro secciones: la barra de herramientas, el modo de cuadrícula, el modo de lista y la barra lateral. Trataremos de las tres primeras secciones de este artículo, y luego en el siguiente tutorial, modificaremos la barra lateral y realizaremos algunas correcciones de CSS.

Si miras cualquier página de categoría de nuestro tema, en la actualidad se verá algo como esto:

Category Page before editingCategory Page before editingCategory Page before editing

Si bien queremos hacer que se vea así:

HTML design Category PageHTML design Category PageHTML design Category Page

Si te das cuenta, nuestra página de categoría actual tiene amplios espacios vacíos a la izquierda y derecha. Tenemos que averiguar por qué el área de contenido no está tomando suficiente espacio. Veamos primero qué plantilla es responsable de procesar esta página. Podemos hacer esto permitiendo sugerencias de plantilla desde el panel de administración, como lo ha hecho varias veces antes en esta serie.

Aquí descubrimos que tenía un diseño de tres columnas que representaba esta página, y esta es la razón por la que hay espacio vacío a la izquierda, ya que no se asignan bloques a la barra lateral izquierda.

Template Hints for Category PageTemplate Hints for Category PageTemplate Hints for Category Page

Para que esta página se vea como nuestro diseño HTML, lo cambiaremos a dos columnas. Desde el panel de administración, vaya a Catálogo > Administrar categorías > Diseño personalizado > Diseño de página y cámbielo a 2 columnas con la barra de la izquierda.

Changing Page LayoutChanging Page LayoutChanging Page Layout

Ahora nuestra página debe tener un diseño de dos columnas con una barra lateral en el lado izquierdo, así como el requisito de nuestro diseño.

Como en este artículo sólo cambiaremos el área correcta (no la barra lateral), iniciaremos el proceso de edición desde la barra de herramientas. Con las sugerencias de la plantilla activadas, comprobaremos los archivos phtml responsables de la representación, activando nuevamente las sugerencias de la plantilla.

Como hemos descubierto, es este archivo: \ template \ catalog / product / list / toolbar.phtml.

Copiamos eso en nuestro nuevo tema, lo comparamos con el código de nuestro archivo HTML y luego empezamos a hacer cambios. Nuestro código actual del archivo toolbar.phtml tiene este aspecto:

1
<?php if($this->getCollection()->getSize()): ?>
2
<div class="toolbar">
3
    <?php if( $this->isExpanded() ): ?>
4
        <div class="sorter">
5
            <?php if( $this->isEnabledViewSwitcher() ): ?>
6
                <p class="view-mode">
7
                    <?php $_modes = $this->getModes(); ?>
8
                    <?php if($_modes && count($_modes)>1): ?>
9
                        <label><?php echo $this->__('View as') ?></label>
10
                        <?php foreach ($this->getModes() as $_code=>$_label): ?>
11
                            <?php if($this->isModeActive($_code)): ?>
12
                                <strong title="<?php echo $_label ?>" class="<?php echo strtolower($_code); ?>"><?php echo $_label ?></strong>
13
                            <?php else: ?>
14
                                <a href="<?php echo $this->getModeUrl($_code) ?>" title="<?php echo $_label ?>" class="<?php echo strtolower($_code); ?>"><?php echo $_label ?></a>
15
                            <?php endif; ?>
16
                        <?php endforeach; ?>
17
                    <?php endif; ?>
18
                </p>
19
            <?php endif; ?>
20
21
            <div class="sort-by">
22
                <label><?php echo $this->__('Sort By') ?></label>
23
                <select onchange="setLocation(this.value)" title="<?php echo $this->__('Sort By') ?>">
24
                    <?php foreach($this->getAvailableOrders() as $_key=>$_order): ?>
25
                        <option value="<?php echo $this->getOrderUrl($_key, 'asc') ?>"<?php if($this->isOrderCurrent($_key)): ?> selected="selected"<?php endif; ?>>
26
                            <?php echo $this->__($_order) ?>
27
                        </option>
28
                    <?php endforeach; ?>
29
                </select>
30
                <?php if($this->getCurrentDirection() == 'desc'): ?>
31
                    <a href="<?php echo $this->getOrderUrl(null, 'asc') ?>" class="sort-by-switcher sort-by-switcher--desc" title="<?php echo $this->__('Set Ascending Direction') ?>"><?php echo $this->__('Set Ascending Direction') ?></a>
32
                <?php else: ?>
33
                    <a href="<?php echo $this->getOrderUrl(null, 'desc') ?>" class="sort-by-switcher sort-by-switcher--asc" title="<?php echo $this->__('Set Descending Direction') ?>"><?php echo $this->__('Set Descending Direction') ?></a>
34
                <?php endif; ?>
35
            </div>
36
        </div>
37
    <?php endif; ?>
38
    <div class="pager">
39
        <div class="count-container">
40
            <?php if($this->getLastPageNum()>1): ?>
41
                <p class="amount amount--has-pages">
42
                    <?php echo $this->__('%s-%s of %s', $this->getFirstNum(), $this->getLastNum(), $this->getTotalNum()) ?>
43
                </p>
44
            <?php else: ?>
45
                <p class="amount amount--no-pages">
46
                    <strong><?php echo $this->__('%s Item(s)', $this->getTotalNum()) ?></strong>
47
                </p>
48
            <?php endif; ?>
49
50
            <div class="limiter">
51
                <label><?php echo $this->__('Show') ?></label>
52
                <select onchange="setLocation(this.value)" title="<?php echo $this->__('Results per page'); ?>">
53
                <?php foreach ($this->getAvailableLimit() as  $_key=>$_limit): ?>
54
                    <option value="<?php echo $this->getLimitUrl($_key) ?>"<?php if($this->isLimitCurrent($_key)): ?> selected="selected"<?php endif ?>>
55
                        <?php echo $_limit ?>
56
                    </option>
57
                <?php endforeach; ?>
58
                </select>
59
            </div>
60
        </div>
61
62
        <?php echo $this->getPagerHtml() ?>
63
64
    </div>
65
</div>
66
<?php endif ?>

Tenemos que compararlo con el código HTML responsable de la parte barra de herramientas, que es la siguiente:

1
<div class="toolbar">
2
  <div class="sorter">
3
    <div class="view-mode"><a href="productlitst.html" class="list">List</a><a href="#" class="grid active">Grid</a></div>
4
    <div class="sort-by">Sort by :
5
      <select name="" >
6
        <option value="Default" selected>Default</option>
7
        <option value="Name">Name</option>
8
        <option value="Price">Price</option>
9
      </select>
10
    </div>
11
    <div class="limiter">Show :
12
      <select name="" >
13
        <option value="3" selected>3</option>
14
        <option value="6">6</option>
15
        <option value="9">9</option>
16
      </select>
17
    </div>
18
  </div>
19
</div>

Comenzaremos a modificar este código introduciendo las etiquetas dinámicas y las diferentes sentencias for y if. Por ejemplo, para representar los enlaces de los modos de cuadrícula y lista para el modo de visualización, agregaremos este código:

1
<?php if($_modes && count($_modes)>1): ?>
2
<?php foreach ($this->getModes() as $_code=>$_label): ?>
3
  <?php if($this->isModeActive($_code)): ?>
4
    <a title="<?php echo $_label ?>" href="#" class="<?php echo strtolower($_label) ?> active"><?php echo $_label ?></a>
5
    <?php else: ?>
6
      <a title="<?php echo $_label ?>" href="<?php echo $this->getModeUrl($_code) ?>" class="<?php echo strtolower($_label) ?>"><?php echo $_label ?></a>
7
     <?php endif ?>
8
  <?php endforeach; ?>
9
<?php endif ?>

Lo que este código esencialmente hace es iterar sobre todos los modos activos (lista y cuadrícula), y luego lista una etiqueta de anclaje para cada uno de ellos. Aquí, muy inteligentemente, les hemos asignado diferentes clases y títulos, usando la variable $ _label, que será diferente para cada modo.

Del mismo modo, puede modificar las partes de clasificación sort-by y limitación limiter comparándolas con el archivo toolbar.phtml real. Después de las modificaciones, el código final para este archivo se verá así:

1
<?php if($this->getCollection()->getSize()): ?>
2
    <div class="toolbar">
3
      <?php if( $this->isExpanded() ): ?>
4
        <div class="sorter">
5
          <?php if( $this->isEnabledViewSwitcher() ): ?>
6
            <div class="view-mode">
7
              <?php $_modes = $this->getModes(); ?>
8
              <?php if($_modes && count($_modes)>1): ?>
9
                <?php foreach ($this->getModes() as $_code=>$_label): ?>
10
                  <?php if($this->isModeActive($_code)): ?>
11
                    <a title="<?php echo $_label ?>" href="#" class="<?php echo strtolower($_label) ?> active"><?php echo $_label ?></a>
12
                    <?php else: ?>
13
                      <a title="<?php echo $_label ?>" href="<?php echo $this->getModeUrl($_code) ?>" class="<?php echo strtolower($_label) ?>"><?php echo $_label ?></a>
14
                     <?php endif ?>
15
                  <?php endforeach; ?>
16
                <?php endif ?>
17
            </div>
18
          <?php endif ?>
19
20
          <div class="sort-by">Sort by :
21
            <select onchange="setLocation(this.value)" title="<?php echo $this->__('Sort By') ?>">
22
            <?php foreach($this->getAvailableOrders() as $_key=>$_order): ?>
23
              <option value="<?php echo $this->getOrderUrl($_key, 'asc') ?>"<?php if($this->isOrderCurrent($_key)): ?> selected="selected"<?php endif; ?>>
24
                          <?php echo $this->__($_order) ?>
25
                      </option>              
26
            <?php endforeach; ?>
27
            </select>
28
            <?php if($this->getCurrentDirection() == 'desc'): ?>
29
                  <a href="<?php echo $this->getOrderUrl(null, 'asc') ?>" class="sort-by-switcher sort-by-switcher--desc" title="<?php echo $this->__('Set Ascending Direction') ?>"><?php echo $this->__('Set Ascending Direction') ?></a>
30
              <?php else: ?>
31
                  <a href="<?php echo $this->getOrderUrl(null, 'desc') ?>" class="sort-by-switcher sort-by-switcher--asc" title="<?php echo $this->__('Set Descending Direction') ?>"><?php echo $this->__('Set Descending Direction') ?></a>
32
              <?php endif; ?>
33
          </div>
34
          <div class="limiter"><?php echo $this->__('Show: ') ?>
35
            <select onchange="setLocation(this.value)" title="<?php echo $this->__('Results per page'); ?>">
36
              <?php foreach ($this->getAvailableLimit() as  $_key=>$_limit): ?>
37
                  <option value="<?php echo $this->getLimitUrl($_key) ?>"<?php if($this->isLimitCurrent($_key)): ?> selected="selected"<?php endif ?>>
38
                      <?php echo $_limit ?>
39
                  </option>
40
              <?php endforeach; ?>
41
              </select>
42
          </div>
43
        </div>
44
        <?php endif ?>
45
        <?php echo $this->getPagerHtml() ?>
46
    </div>
47
<?php endif ?>

Y si actualizamos la página ahora, se verá algo así. Todo está en su lugar, pero el CSS está bastante apagado, que vamos a arreglar en el próximo artículo.

Toolbar after editingToolbar after editingToolbar after editing

Ahora es el momento de cambiar los productos reales que se muestran en esta página. Los productos aquí se pueden mostrar de dos maneras diferentes, es decir, modo de lista y modo de cuadrícula. Si activamos sugerencias de plantillas para averiguar el archivo responsable de esta parte, veremos que el código para el modo de cuadrícula y de lista está escrito en el mismo archivo, que es frontend \ rwd \ default \ template \ catalog / product / list .phtml.

El código de lista en este archivo está en las líneas 44 a 116, que es:

1
<?php // List mode ?>

2
    <?php if($this->getMode()!='grid'): ?>
3
    <?php $_iterator = 0; ?>
4
    <ol class="products-list" id="products-list">
5
    <?php foreach ($_productCollection as $_product): ?>
6
        <li class="item<?php if( ++$_iterator == sizeof($_productCollection) ): ?> last<?php endif; ?>">
7
            <?php // Product Image ?>

8
            <a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" class="product-image">
9
                <?php /* Based on the native RWD styling, product images are displayed at a max of ~400px wide when viewed on a

10
                        one column page layout with four product columns from a 1280px viewport. For bandwidth reasons,

11
                        we are going to serve a 300px image, as it will look fine at 400px and most of the times, the image

12
                        will be displayed at a smaller size (eg, if two column are being used or viewport is smaller than 1280px).

13
                        This $_imgSize value could even be decreased further, based on the page layout

14
                        (one column, two column, three column) and number of product columns. */ ?>
15
                <?php $_imgSize = 300; ?>
16
                <img id="product-collection-image-<?php echo $_product->getId(); ?>"
17
                     src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->keepFrame(false)->resize($_imgSize); ?>"
18
                     alt="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" />
19
            </a>
20
            <?php // Product description ?>

21
            <div class="product-shop">
22
                <div class="f-fix">
23
                    <div class="product-primary">
24
                        <?php $_productNameStripped = $this->stripTags($_product->getName(), null, true); ?>
25
                        <h2 class="product-name"><a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $_productNameStripped; ?>"><?php echo $_helper->productAttribute($_product, $_product->getName() , 'name'); ?></a></h2>
26
                        <?php if($_product->getRatingSummary()): ?>
27
                        <?php echo $this->getReviewsSummaryHtml($_product) ?>
28
                        <?php endif; ?>
29
                        <?php
30
                        // Provides extra blocks on which to hang some features for products in the list

31
                        // Features providing UI elements targeting this block will display directly below the product name

32
                        if ($this->getChild('name.after')) {
33
                            $_nameAfterChildren = $this->getChild('name.after')->getSortedChildren();
34
                            foreach ($_nameAfterChildren as $_nameAfterChildName) {
35
                                $_nameAfterChild = $this->getChild('name.after')->getChild($_nameAfterChildName);
36
                                $_nameAfterChild->setProduct($_product);
37
                                echo $_nameAfterChild->toHtml();
38
                            }
39
                        }
40
                        ?>
41
                    </div>
42
                    <div class="product-secondary">
43
                        <?php echo $this->getPriceHtml($_product, true) ?>
44
                    </div>
45
                    <div class="product-secondary">
46
                        <?php if(!$_product->canConfigure() && $_product->isSaleable()): ?>
47
                            <p class="action"><button type="button" title="<?php echo $this->__('Add to Cart') ?>" class="button btn-cart" onclick="setLocation('<?php echo $this->getAddToCartUrl($_product) ?>')"><span><span><?php echo $this->__('Add to Cart') ?></span></span></button></p>
48
                        <?php elseif($_product->getStockItem() && $_product->getStockItem()->getIsInStock()): ?>
49
                            <p class="action"><a title="<?php echo $this->__('View Details') ?>" class="button" href="<?php echo $_product->getProductUrl() ?>"><?php echo $this->__('View Details') ?></a></p>
50
                        <?php else: ?>
51
                            <p class="action availability out-of-stock"><span><?php echo $this->__('Out of stock') ?></span></p>
52
                        <?php endif; ?>
53
                        <ul class="add-to-links">
54
                            <?php if ($this->helper('wishlist')->isAllow()) : ?>
55
                                <li><a href="<?php echo $this->helper('wishlist')->getAddUrl($_product) ?>" class="link-wishlist"><?php echo $this->__('Add to Wishlist') ?></a></li>
56
                            <?php endif; ?>
57
                            <?php if($_compareUrl=$this->getAddToCompareUrl($_product)): ?>
58
                                <li><span class="separator">|</span> <a href="<?php echo $_compareUrl ?>" class="link-compare"><?php echo $this->__('Add to Compare') ?></a></li>
59
                            <?php endif; ?>
60
                        </ul>
61
                    </div>
62
                    <div class="desc std">
63
                        <?php echo $_helper->productAttribute($_product, $_product->getShortDescription(), 'short_description') ?>
64
                        <a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $_productNameStripped ?>" class="link-learn"><?php echo $this->__('Learn More') ?></a>
65
                    </div>
66
                </div>
67
            </div>
68
        </li>
69
    <?php endforeach; ?>
70
    </ol>
71
    <script type="text/javascript">decorateList('products-list', 'none-recursive')</script>

Ahora tenemos que compararlo con el código de la lista HTML en la lista de productos.html en nuestra plantilla HTML.

1
<ul class="products-listItem">
2
  <li class="products">
3
    <div class="offer">New</div>
4
    <div class="thumbnail"><img src="images/products/small/products-05.png" alt="Product Name"></div>
5
    <div class="product-list-description">
6
      <div class="productname">Lincoln Corner Unit Products</div>
7
      <p><img src="images/star.png" alt=""><a href="#" class="review_num">02 Review(s)</a></p>
8
      <p>Proin lectus ipsum, gravida et mattis vulputate, tristique ut lectus. Sed et lorem nunc. Vestibulum ante ipsum primis in faucibus orci luctus et ultri ces posuere cubilia curae. Proin lectus ipsum, gravida etds mattis vulputate, tristique ut lectus. Sed et lorem nunc...</p>
9
      <div class="list_bottom">
10
        <div class="price"><span class="new_price">450.00<sup>$</sup></span><span class="old_price">450.00<sup>$</sup></span></div>
11
        <div class="button_group">
12
          <button class="button">Add To Cart</button>
13
        
14
        </div>
15
      </div>
16
    </div>
17
  </li>
18
</ul>
19
            

La modificación de este código es bastante simple. Utilizaremos estas líneas de inicialización:

1
<?php // List mode ?>

2
<?php if($this->getMode()!='grid'): ?>
3
<?php $_iterator = 0; ?>

Entonces pondremos un bucle for alrededor de la etiqueta li:

1
<?php foreach ($_productCollection as $_product): ?>

Y por último reemplazaremos el nombre del producto, el precio, la descripción, el vínculo del archivo de imagen y la URL con las etiquetas dinámicas. El código final se verá así:

1
<?php // List mode ?>

2
<?php if($this->getMode()!='grid'): ?>
3
<?php $_iterator = 0; ?>
4
<ol class="products-list" id="products-list">
5
<?php foreach ($_productCollection as $_product): ?>
6
    <li class="products item<?php if( ++$_iterator == sizeof($_productCollection) ): ?> last<?php endif; ?>">
7
        
8
          <div class="thumbnail">
9
            <?php $_imgSize = 300; ?>
10
            <img id="product-collection-image-<?php echo $_product->getId(); ?>"
11
                 src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->keepFrame(false)->resize($_imgSize); ?>"
12
                 alt="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" />
13
          </div>
14
          <div class="product-list-description">
15
            <div class="productname"><?php echo $_helper->productAttribute($_product, $_product->getName() , 'name'); ?></div>
16
            <p><?php if($_product->getRatingSummary()): ?>
17
              <?php echo $this->getReviewsSummaryHtml($_product) ?>
18
              <?php endif; ?>
19
            </p>
20
            <p><?php echo $_helper->productAttribute($_product, $_product->getShortDescription(), 'short_description') ?></p>
21
            <div class="list_bottom">
22
              <div class="price"><?php echo $this->getPriceHtml($_product, true) ?></div>
23
              <div class="button_group">
24
                <button type="button" title="<?php echo $this->__('Add to Cart') ?>" class="button btn-cart" onclick="setLocation('<?php echo $this->getAddToCartUrl($_product) ?>')"><span><span><?php echo $this->__('Add to Cart') ?></span></span></button>
25
              </div>
26
            </div>
27
          </div>
28
    </li>
29
<?php endforeach; ?>
30
</ol>
31
<script type="text/javascript">decorateList('products-list', 'none-recursive')</script>

Ahora, si actualizamos la página, veremos que la página de categorías en modo de lista se verá así. Sé que no es lo que queremos que parezca, pero todo nuestro HTML está en su lugar, por lo que ahora sólo tenemos que modificar su CSS, que vamos a hacer en el próximo tutorial.

List Mode after editingList Mode after editingList Mode after editing

Ahora llegando al modo de cuadrícula, el código para eso es de 118 a 176 en el mismo archivo list.phtml.

1
<?php // Grid Mode ?>

2
3
<?php $_collectionSize = $_productCollection->count() ?>
4
<?php $_columnCount = $this->getColumnCount(); ?>
5
<ul class="products-grid products-grid--max-<?php echo $_columnCount; ?>-col">
6
    <?php $i=0; foreach ($_productCollection as $_product): ?>
7
        <?php /*if ($i++%$_columnCount==0): ?>

8
        <?php endif*/ ?>
9
        <li class="item<?php if(($i-1)%$_columnCount==0): ?> first<?php elseif($i%$_columnCount==0): ?> last<?php endif; ?>">
10
            <a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" class="product-image">
11
                <?php $_imgSize = 210; ?>
12
                <img id="product-collection-image-<?php echo $_product->getId(); ?>"
13
                     src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->resize($_imgSize); ?>"
14
                     alt="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" />
15
            </a>
16
            <div class="product-info">
17
                <h2 class="product-name"><a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->stripTags($_product->getName(), null, true) ?>"><?php echo $_helper->productAttribute($_product, $_product->getName(), 'name') ?></a></h2>
18
                <?php
19
                // Provides extra blocks on which to hang some features for products in the list

20
                // Features providing UI elements targeting this block will display directly below the product name

21
                if ($this->getChild('name.after')) {
22
                    $_nameAfterChildren = $this->getChild('name.after')->getSortedChildren();
23
                    foreach ($_nameAfterChildren as $_nameAfterChildName) {
24
                        $_nameAfterChild = $this->getChild('name.after')->getChild($_nameAfterChildName);
25
                        $_nameAfterChild->setProduct($_product);
26
                        echo $_nameAfterChild->toHtml();
27
                    }
28
                }
29
                ?>
30
                <?php echo $this->getPriceHtml($_product, true) ?>
31
                <?php if($_product->getRatingSummary()): ?>
32
                <?php echo $this->getReviewsSummaryHtml($_product, 'short') ?>
33
                <?php endif; ?>
34
                <div class="actions">
35
                    <?php if(!$_product->canConfigure() && $_product->isSaleable()): ?>
36
                        <button type="button" title="<?php echo $this->__('Add to Cart') ?>" class="button btn-cart" onclick="setLocation('<?php echo $this->getAddToCartUrl($_product) ?>')"><span><span><?php echo $this->__('Add to Cart') ?></span></span></button>
37
                    <?php elseif($_product->getStockItem() && $_product->getStockItem()->getIsInStock()): ?>
38
                        <a title="<?php echo $this->__('View Details') ?>" class="button" href="<?php echo $_product->getProductUrl() ?>"><?php echo $this->__('View Details') ?></a>
39
                    <?php else: ?>
40
                        <p class="availability out-of-stock"><span><?php echo $this->__('Out of stock') ?></span></p>
41
                    <?php endif; ?>
42
                    <ul class="add-to-links">
43
                        <?php if ($this->helper('wishlist')->isAllow()) : ?>
44
                            <li><a href="<?php echo $this->helper('wishlist')->getAddUrl($_product) ?>" class="link-wishlist"><?php echo $this->__('Add to Wishlist') ?></a></li>
45
                        <?php endif; ?>
46
                        <?php if($_compareUrl=$this->getAddToCompareUrl($_product)): ?>
47
                            <li><span class="separator">|</span> <a href="<?php echo $_compareUrl ?>" class="link-compare"><?php echo $this->__('Add to Compare') ?></a></li>
48
                        <?php endif; ?>
49
                    </ul>
50
                </div>
51
            </div>
52
        </li>
53
        <?php /*if ($i%$_columnCount==0 || $i==$_collectionSize): ?>

54
        <?php endif*/ ?>
55
    <?php endforeach ?>
56
</ul>
57
<script type="text/javascript">decorateGeneric($$('ul.products-grid'), ['odd','even','first','last'])</script>
58
<?php endif; ?>

El código HTML se ve así en el archivo productgrid.html de nuestra plantilla HTML:

1
<div class="row">
2
  <div class="col-md-4 col-sm-6">
3
    <div class="products">
4
      <div class="main">
5
        <div class="view view-eighth">
6
          <img src="images/products/small/products-02.jpg" />
7
        	<div class="mask">
8
            	<a href="#" class="info">Read More</a>
9
        	</div>
10
            <div class="productname">Iphone 5s Gold 32 Gb 2013</div>
11
      		<h4 class="price">$451.00</h4>
12
    	</div>
13
		</div>
14
    </div>
15
  </div>
16
</div>

La modificación de esta parte será bastante similar a lo que hicimos en la parte de la lista. Primero haremos una inicialización, como en el archivo list.phtml por defecto.

1
<?php // Grid Mode ?>

2
3
<?php $_collectionSize = $_productCollection->count() ?>
4
<?php $_columnCount = $this->getColumnCount(); ?>

A continuación vamos a envolver cada elemento li dentro de un bucle for para iterar sobre todos los productos.

1
<?php $i=0; foreach ($_productCollection as $_product): ?>

Por último, reemplazaremos los atributos del producto, como nombre del producto, precio, descripción, etc., con las etiquetas dinámicas relevantes. Puede encontrarlos muy convenientemente desde el archivo real list.phtml.

El código final se verá así:

1
<?php // Grid Mode ?>

2
3
<?php $_collectionSize = $_productCollection->count() ?>
4
<?php $_columnCount = $this->getColumnCount(); ?>
5
<ul class="products-grid products-grid--max-<?php echo $_columnCount; ?>-col">
6
    <?php $i=0; foreach ($_productCollection as $_product): ?>
7
        <?php /*if ($i++%$_columnCount==0): ?>

8
        <?php endif*/ ?>
9
        <li class="item<?php if(($i-1)%$_columnCount==0): ?> first<?php elseif($i%$_columnCount==0): ?> last<?php endif; ?>">
10
            <div class="view view-eighth">
11
<img src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->resize($_imgSize); ?>"
12
                     alt="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>"/>
13
<div class="mask">
14
    <a href="<?php echo $_product->getProductUrl() ?>" class="info">Add to Cart</a>
15
</div>
16
  <div class="productname"><?php echo $this->stripTags($_product->getName(), null, true) ?></div>
17
<h4 class="price"><?php echo $this->getPriceHtml($_product, true) ?>
18
                </h4>
19
</div>
20
        </li>
21
        <?php /*if ($i%$_columnCount==0 || $i==$_collectionSize): ?>

22
        <?php endif*/ ?>
23
    <?php endforeach ?>
24
</ul>
25
<script type="text/javascript">decorateGeneric($$('ul.products-grid'), ['odd','even','first','last'])</script>
26
<?php endif; ?>

Ahora, si actualiza la página, el modo de cuadrícula se verá así:

Grid Mode after editingGrid Mode after editingGrid Mode after editing

En este artículo, hemos modificado las secciones de la barra de herramientas y la lista y la cuadrícula de esta página. En el siguiente artículo vamos a modificar la barra lateral, y hacer algunas correcciones de estilo CSS. Al final del próximo artículo, nuestra página de categoría se verá muy similar al diseño HTML.

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.