I have a multidimensional array that i send to a template where i use smarty.
The array looks like:
array (size=2)
'gender' =>
array (size=2)
0 => string 'male' (length=4)
1 => string 'female' (length=6)
'states' =>
array (size=11)
0 => string 'Ciudad Autonoma de Buenos Aires' (length=31)
1 => string 'Buenos Aires' (length=12)
2 => string 'Catamarca' (length=9)
3 => string 'Chaco' (length=5)
4 => string 'Chubut' (length=6)
5 => string 'Cordoba' (length=7)
6 => string 'Corrientes' (length=10)
7 => string 'Entre Rios' (length=10)
8 => string 'Formosa' (length=7)
9 => string 'Jujuy' (length=5)
10 => string 'La Pampa' (length=8)
what i want to achieve is this: i can only show 4 or less elements from each array depending on how many elements it has. For example, for the subarray "gender" i show both male and female. But, for the subarray "states" i only have to show the first 4 elements, and then to add a legend with a link "show more".
This is so far what i coded:
{if $ns eq 'states'}
<dt>Provincia</dt>
{assign var="n" value="0"}
{counter start=0 print=false assign=n}
{foreach from=$r key=k item=v}
{counter print=false}
{if counter lt 3}
<dd>{$v}</dd>
{elseif counter eq 3}
<dd>Ver más<dd>
{/if}
{/foreach}
n = {$n}
{/if}
It's not giving me the results i want. I don't know how to "hide" the elements when they are more than 4. I could only iterate 4 times, but in that case, how would i manipulate the subarray if i don't have a foreach?
The Output should look like this:
Gender
Male
Female
States
Ciudad Autonoma de Buenos Aires
Buenos Aires
Catamarca
Chaco
See More>>
With Smarty 3.x, you can use @iteration
property or @index
property to count 'loop'
{if $ns eq 'states'}
<dt>Provincia</dt>
{foreach $r AS $k=>$v}
{if $v@iteration lt 3}
<dd>{$v}</dd>
{else}
<dd>Ver más<dd>
{break}
{/if}
{/foreach}
n = {$n}
{/if}
<style type="text/css">
{literal}
.el-tohide {display:none;}
{/literal}
</style>
{if $ns eq 'states'}
<dt>Provincia</dt>
{foreach $r AS $k=>$v}
<dd class="{if $v@iteration gt 3}el-states el-tohide{/if}">{$v}</dd>
{if $v@last && $v@iteration gt 3}
<dd class="el-click">Ver más<dd>
{/if}
{/foreach}
n = {$n}
{/if}
<script type="text/javascript">
{literal}
$('.el-click').on('click', function (){
if ($('.el-states').hasClass('el-tohide'))
$('.el-states').removeClass('el-tohide');
else
$('.el-states').addClass('el-tohide');
});
{/literal}
</script>
Just AS IS not sure is functionnal but i give you the general idea. I'm supposing you're using Jquery.