Search code examples
phploopsprestashopsmarty

PrestaShop and Smarty: cutting through the loop


I am developing a website for a client, and I have been asked to display the features using two columns instead of the usual one. There will be three columns on the product page One column contains the picture of the product and the two others are the features. The latter are features, but the first columns contains general characteristics (reference name, colour, adhesive type,...) of the item while the other columns will be about dimensions (margin, padding, pitch, height,...).

I see in "product-details.tpl" that the items are looped from "$product=grouped_features" array, and as my technical references are containing 16 datafields, I'd like to interrupt the loop at the 8th feature on the first column, and resume the loop the next column.

I know that in some templating languages (Jinja2, Twig, Handlebars), it is possible to do something like that, but I cannot manage to find this with Smarty. Would I have to change something in the deep code?

More than words, an example with pseudocode;

// Column N°1
FOREACH $product.grouped_features START=1(i) STOP=8(i)
    $feature.name(i)
    $feature.value(i)
ENDFOREACH

// Column N°2
FOREACH $product.grouped_features START=9(i) STOP=16(i)
    $feature.name(i)
    $feature.value(i)
ENDFOREACH

(i) being the iteration.

I tried this solution, but it only shows me one iteration. To test, I only have 6 features, I set $smarty.foreach.featureCount.iteration == 4 but it only shows me the 4th value :

{foreach from=$product.grouped_features item=feature name=featureCount}
    {if $smarty.foreach.featureCount.iteration == 4}
        <dt class="name">{$feature.name}</dt>
        <dd class="value">{$feature.value|escape:'htmlall'|nl2br nofilter}</dd>
        {break}
     {/if}
{/foreach}

I have been looking about this for some time now and I run out of ideas. Is that even possible? I am running PrestaShop 1.7.3.


Solution

  • Using your example with 6 features, you could try this:

    {foreach from=$product.grouped_features item=feature name=featureCount}
        <dt class="name">{$feature.name}</dt>
        <dd class="value">{$feature.value|escape:'htmlall'|nl2br nofilter}</dd>
        {if $feature@iteration == 4}
            {break}
        {/if}
    {/foreach}
    

    Your mistake was printing the features within your break condition. If you do that before the if-condition, it should work.


    For the second feature column though, you will have to change the logic a bit, since you cant use break but you have to leave out the first X features. Here you can use the attempt of the second answer from your linked question:

    {foreach from=$product.grouped_features item=feature name=featureCount}
        {if $feature@iteration > 4}
            <dt class="name">{$feature.name}</dt>
            <dd class="value">{$feature.value|escape:'htmlall'|nl2br nofilter}</dd>
        {/if}
    {/foreach}