Get Smarty

Donate

Paypal

Smarty Icon

You may use the Smarty logo according to the trademark notice.

Smarty Template Engine Smarty Template Engine

For sponsorship, advertising, news or other inquiries, contact us at:

Sites Using Smarty

Advertisement

section,sectionelse

Nombre del Atributo Tipo Requerido Default Descripción
name string Si n/a El nombre de la section
loop mixed Si n/a El nombre de la variable para determinar el número de iteracciones
start integer No 0 La posición del índice de la section donde va a comenzar. Si el valor es negativo, la posición del inicio se calculara a partir del final de la matriz. Por ejemplo, si hubieran 7 valores en la matriz y comienza por -2, el índice inicial es 5. Valores inválidos (valores fuera del tamaño de la matriz) son automáticamente truncados para el valor valido mas próximo.
step integer No 1 El valor del step que sera usado para el loop de la matriz. Por ejemplo, step=2 realizara el loop con los índices 0,2,4, etc. Si step es negativo, este avanzara en la matriz de atras para adelante.
max integer No n/a Defíne el número máximo de ciclos(loops) para la section.
show boolean No true Determina cuando mostrar o no esta sección

Las section del template son usada para realizar un ciclo(loop) de un arreglo de datos. (al agiual que un {foreach}). Todas las etiquetas section deben tener su par /section. Los parámetros requeridos son name y loop. El nombre de la section puede ser el que usted quiera, formado por letras, números y subrayados. Las sections pueden ser anidadas, y los nombres de la section anidadas deben ser diferentes unos de otros. Las variables del loop (normalmente una matriz de valores) determina el número de veces del loop de la section. Cuando estuviera mostrando una variable dentro de una section, el nombre de la section debe estar al lado de la variable dentro de corchetes []. sectionelse es ejecutado cuando no hubiera valores para la variable del loop(ciclo).

Example 7.17. section


<?php

$data = array(1000,1001,1002);
$smarty->assign('custid',$data);

?>


{* this example will print out all the values of the $custid array *}
{section name=customer loop=$custid}
  id: {$custid[customer]}<br />
{/section}
<hr />
{*  print out all the values of the $custid array reversed *}
{section name=foo loop=$custid step=-1}
  {$custid[foo]}<br />
{/section}

  

The above example will output:


id: 1000<br />
id: 1001<br />
id: 1002<br />
<hr />
id: 1002<br />
id: 1001<br />
id: 1000<br />

  

Otro par de ejemplos sin un arreglo asignado.


{section name=foo start=10 loop=20 step=2}
  {$smarty.section.foo.index}
{/section}
<hr />
{section name=bar loop=21 max=6 step=-2}
  {$smarty.section.bar.index}
{/section}

Esta es la salida del ejemplo de arriba:

  
10 12 14 16 18
<hr />
20 18 16 14 12 10

  

Example 7.18. loop(ciclo) de la variable section


<?php

$id = array(1001,1002,1003);
$smarty->assign('custid',$id);

$fullnames = array('John Smith','Jack Jones','Jane Munson');
$smarty->assign('name',$fullnames);

$addr = array('253 N 45th', '417 Mulberry ln', '5605 apple st');
$smarty->assign('address',$addr);

?>


{* la variable del loop solo determina el número de veces del ciclo.
   Usted puede accesar a cualquier variable del template dentro de la section.
   Este ejemplo asume que $custid, $name y $address son todas matrizes
   conteniendo el mismo número de valores *}
{section name=customer loop=$custid}
	id: {$custid[customer]}&lt;br&gt;
	name: {$name[customer]}&lt;br&gt;
	address: {$address[customer]}&lt;br&gt;
	&lt;p&gt;
{/section}

La salida del ajemplo de arriba:


<p>
  id: 1000<br />
  name: John Smith<br />
  address: 253 N 45th
</p>
<p>
  id: 1001<br />
  name: Jack Jones<br />
  address: 417 Mulberry ln
</p>
<p>
  id: 1002<br />
  name: Jane Munson<br />
  address: 5605 apple st
</p>

  

Example 7.19. Nombres de section


{*
   El nombre de la section puede ser el que usted quiera,
   y es usado para referenciar los datos dentro de una section 
*}
{section name=anything loop=$custid}
<p>
  id: {$custid[anything]}<br />
  name: {$name[anything]}<br />
  address: {$address[anything]}
</p>
{/section}

  

Example 7.20. sections anidadas


<?php

$id = array(1001,1002,1003);
$smarty->assign('custid',$id);

$fullnames = array('John Smith','Jack Jones','Jane Munson');
$smarty->assign('name',$fullnames);

$addr = array('253 N 45th', '417 Mulberry ln', '5605 apple st');
$smarty->assign('address',$addr);

$types = array(
           array( 'home phone', 'cell phone', 'e-mail'),
           array( 'home phone', 'web'),
           array( 'cell phone')
         );
$smarty->assign('contact_type', $types);

$info = array(
           array('555-555-5555', '666-555-5555', 'john@myexample.com'),
           array( '123-456-4', 'www.example.com'),
           array( '0457878')
        );
$smarty->assign('contact_info', $info);

?>
  

{* Las sections pueden ser anidados tan profundamente como usted quiera.
   Con las sections anidadas, usted puede accesar a estructuras complejas,
   como una matriz multi-dimensional. En este ejemplo, $contact_type[customer] 
   es una matriz de tipos de contacto para el cliente actual. *}
{section name=customer loop=$custid}
<hr>
  id: {$custid[customer]}<br />
  name: {$name[customer]}<br />
  address: {$address[customer]}<br />
  {section name=contact loop=$contact_type[customer]}
    {$contact_type[customer][contact]}: {$contact_info[customer][contact]}<br />
  {/section}
{/section}

la salida del ejemplo de arriba:


<hr>
  id: 1000<br />
  name: John Smith<br />
  address: 253 N 45th<br />
    home phone: 555-555-5555<br />
    cell phone: 666-555-5555<br />
    e-mail: john@myexample.com<br />
<hr>
  id: 1001<br />
  name: Jack Jones<br />
  address: 417 Mulberry ln<br />
    home phone: 123-456-4<br />
    web: www.example.com<br />
<hr>
  id: 1002<br />
  name: Jane Munson<br />
  address: 5605 apple st<br />
    cell phone: 0457878<br />

  

Example 7.21. sections y matrices asociativas

  
<?php

$data = array(
          array('name' => 'John Smith', 'home' => '555-555-5555',
                'cell' => '666-555-5555', 'email' => 'john@myexample.com'),
          array('name' => 'Jack Jones', 'home' => '777-555-5555',
                'cell' => '888-555-5555', 'email' => 'jack@myexample.com'),
          array('name' => 'Jane Munson', 'home' => '000-555-5555',
                'cell' => '123456', 'email' => 'jane@myexample.com')
        );
$smarty->assign('contacts',$data);

?>

  

{*
   Este es un ejemplo que muestra los datos de una matriz asociativa 
   dentro de una section 
*}
{section name=customer loop=$contacts}
<p>
  name: {$contacts[customer].name}<br />
  home: {$contacts[customer].home}<br />
  cell: {$contacts[customer].cell}<br />
  e-mail: {$contacts[customer].email}
</p>
{/section}

  

Esta es la salida del ejemplo de arriba:


<p>
  name: John Smith<br />
  home: 555-555-5555<br />
  cell: 666-555-5555<br />
  e-mail: john@myexample.com
</p>
<p>
  name: Jack Jones<br />
  home phone: 777-555-5555<br />
  cell phone: 888-555-5555<br />
  e-mail: jack@myexample.com
</p>
<p>
  name: Jane Munson<br />
  home phone: 000-555-5555<br />
  cell phone: 123456<br />
  e-mail: jane@myexample.com
</p>

  

Ejemplo usando una base de datos(eg usando Pear o Adodb)

  
<?php

$sql = 'select id, name, home, cell, email from contacts';
$smarty->assign('contacts',$db->getAll($sql) );

?>


{*
   salida de la base de datos, resultado en una tabla
*}
<table>
<tr><th>&nbsp;</th><th>Name></th><th>Home</th><th>Cell</th><th>Email</th></tr>
{section name=co loop=$contacts}
  <tr>
    <td><a href="view.php?id={$contacts[co].id}">view<a></td>
    <td>{$contacts[co].name}</td>
    <td>{$contacts[co].home}</td>
    <td>{$contacts[co].cell}</td>
    <td>{$contacts[co].email}</td>
  <tr>
{/section}
</table>


Example 7.22. {sectionelse}


{* sectionelse se ejecutara si no hubieran valores en $custid *}
{section name=customer loop=$custid}
  id: {$custid[customer]}<br />
{sectionelse}
  there are no values in $custid.
{/section}

  

Las sections también tiene sus propias variables que manipulan las propiedades de section. Estas son indicadas asi: {$smarty.section.sectionname.varname}

Note

NOTA: a partir de Smarty 1.5.0, la sintaxis de las variables de las propiedades de section ha sido cambiadas de {%sectionname.varname%} a {$smarty.section.sectionname.varname}. La sintaxis antigua es aun soportada, pero usted puede ver la referencia de la sintaxis nueva en los ejemplos del manual.

index

index es usado para mostrar el índice actual del cliclo(loop), comenzando en cero (o comienza con el atributo dado), e incrementando por uno (o por un atributo de paso dado).

Nota Tecnica

Si las propiedades de paso y comienzo del section son modificadas, entonces estas funcionan igual a las propiedades de iteration de la section, exepto que comienzan en 0 en vez de 1.

Example 7.23. {section} propiedades del index


{* FYI, $custid[customer.index] y $custid[customer] are identical in meaning *}

{section name=customer loop=$custid}
  {$smarty.section.customer.index} id: {$custid[customer]}<br />
{/section}

  

salida del ejemplo de arriba:


0 id: 1000<br />
1 id: 1001<br />
2 id: 1002<br />

   

index_prev

El index_prev es usado para mostrar el índice anterior del loop(ciclo). del primer loop(ciclo) esto es definido como -1.

index_next

El index_next es usado para mostrar el próximo indice del loop. del último loop, esto es uno mas que el índice actual( respetando la definición del atributo step que se a dado.)

Example 7.24. {section} propiedades del index_next y index_prev


<?php

$data = array(1001,1002,1003,1004,1005);
$smarty->assign('custid',$data);

?>


{* FYI, $custid[cus.index] and $custid[cus] are identical in meaning *}

<table>
  <tr>
    <th>index</th><th>id</th>
    <th>index_prev</th><th>prev_id</th>
    <th>index_next</th><th>next_id</th>
  </tr>
{section name=cus loop=$custid}
  <tr>
    <td>{$smarty.section.cus.index}</td><td>{$custid[cus]}</td>
    <td>{$smarty.section.cus.index_prev}</td><td>{$custid[cus.index_prev]}</td>
    <td>{$smarty.section.cus.index_next}</td><td>{$custid[cus.index_next]}</td>
  </tr>
{/section}
</table>

  

la salida del ejemplo de arriba esta contenido en la siguiente tabla:


index  id    index_prev prev_id index_next next_id
0      1001  -1                 1          1002
1      1002  0          1001    2          1003
2      1003  1          1002    3          1004
3      1004  2          1003    4          1005
4      1005  3          1004    5

   

iteration

iteration es usado para mostrar la iteración actual del loop(ciclo).

Note

Esto no es afectado por las propiedades del section start, step y max, distinto de las propriedades del index. Iteration también comineza con 1 en vez de 0 como index. rownum es un alias de iteration, estas funcionan de manera identica.

Example 7.25. {section} propiedades de iteration


<?php

// array of 3000 to 3015
$id = range(3000,3015);
$smarty->assign('custid',$id);

?>


{section name=cu loop=$custid start=5 step=2}
  iteration={$smarty.section.cu.iteration}
  index={$smarty.section.cu.index}
  id={$custid[cu]}<br />
{/section}

  

salida del ejemplo de arriba:


iteration=1 index=5 id=3005<br />
iteration=2 index=7 id=3007<br />
iteration=3 index=9 id=3009<br />
iteration=4 index=11 id=3011<br />
iteration=5 index=13 id=3013<br />
iteration=6 index=15 id=3015<br />

   

Este ejemplo utiliza la propiedad iteration para salida a una tabla bloqueando el encabezado para cada 5 renglones (utilice {if} con el operador mod).


    <table>
{section name=co loop=$contacts}
  {if $smarty.section.co.iteration % 5 == 1}
    <tr><th>&nbsp;</th><th>Name></th><th>Home</th><th>Cell</th><th>Email</th></tr>
  {/if}
  <tr>
    <td><a href="view.php?id={$contacts[co].id}">view<a></td>
    <td>{$contacts[co].name}</td>
    <td>{$contacts[co].home}</td>
    <td>{$contacts[co].cell}</td>
    <td>{$contacts[co].email}</td>
  <tr>
{/section}
</table>

  

first

first es definido como true se la iteración actual de la section es la primera.

last

last es definido como true si la iteración actual del section es la ultima.

Example 7.26. {section} propiedades first y last

En este ciclo de ejemplo el arreglo $customer, en la salida es bloqueado el encabezado en la primera iteracion y en la ultima la salida es bloqueda para el pie de pagina. (Utilice la propiedad section total)


{section name=customer loop=$customers}
  {if $smarty.section.customer.first}
    <table>
    <tr><th>id</th><th>customer</th></tr>
  {/if}

  <tr>
    <td>{$customers[customer].id}}</td>
    <td>{$customers[customer].name}</td>
  </tr>

  {if $smarty.section.customer.last}
    <tr><td></td><td>{$smarty.section.customer.total} customers</td></tr>
    </table>
  {/if}
{/section}

  

rownum

rownum es usado para mostrar la interación actual del loop(ciclo), comenzando con 1. Es un alias para iteration, estas funcionan de modo identico.

loop

loop es usado para mostrar el ultimo número del índice del loop(ciclo) de esta section. Esto puede ser usado dentro o fuera del section.

Example 7.27. {section} propiedades de index


{section name=customer loop=$custid}
  {$smarty.section.customer.index} id: {$custid[customer]}<br />
{/section}

There were {$smarty.section.customer.loop} customers shown above.

  

La salida del ejemplo de arriba:


0 id: 1000<br />
1 id: 1001<br />
2 id: 1002<br />

There were 3 customers shown above.

   

show

showEs usado como parámetro para section. show Es un valor booleano, true o false. Si es false, la section no será mostrada. Si existiera un sectionelse presente, este será alternativamente mostrado.

Example 7.28. section atributos de show


 {* 
    $show_customer_info debe ser pasado de la aplicacion PHP,
    para regular cuando mostrar o no esta section shows
 *}
{section name=customer loop=$custid show=$show_customer_info}
  {$smarty.section.customer.rownum} id: {$custid[customer]}<br />
{/section}

{if $smarty.section.customer.show}
  the section was shown.
{else}
  the section was not shown.
{/if}

  

La salida del ejemplo de arriba:


1 id: 1000<br />
2 id: 1001<br />
3 id: 1002<br />

the section was shown.

   

total

total es usado para mostrar el número de iteraciones que está section tendra. Este puede ser usado dentro o fuera del section.

Example 7.29. {section} propiedades de total


{section name=customer loop=$custid step=2}
  {$smarty.section.customer.index} id: {$custid[customer]}<br />
{/section}

    There were {$smarty.section.customer.total} customers shown above.

  

The above example will output:


0 id: 1000<br />
2 id: 1002<br />
4 id: 1004<br />

There were 3 customers shown above.

   

Ver también {foreach} y $smarty.section.

Comments
No comments for this page.

Advertisement

Sponsors [info]

Sponsors