arraysforeachprestashopsmartyprestashop-1.7

Prestashop 1.7: display categories list in tpl file


I want to display a list of categories in the tpl file of the 404 page.

The categories to be shown are accessible in this array:

    $categories Array (5)
  0 => Array (4)
    id_category => "720"
    name => "brakes"
    link_rewrite => "brakes"
    id_shop => "7"
  1 => Array (4)
    id_category => "721"
    name => "tyres"
    link_rewrite => "tyres"
    id_shop => "7"
  2 => Array (4)
    id_category => "722"
    name => "bumpers"
    link_rewrite => "bumpers"
    id_shop => "7"
  3 => Array (4)
    id_category => "723"
    name => "interiors"
    link_rewrite => "interiors"
    id_shop => "7"
  4 => Array (4)
    id_category => "724"
    name => "accessories"
    link_rewrite => "accessories"
    id_shop => "7"

In the tpl I have added this code:

<ul>
    {foreach from='$categories' item='category'}
        <li>{$category.name}</li>
    {/foreach}
</ul>

I don't understand why the names of the categories are not displayed (I assumed that the foreach loop should display the names of the categories).

Thank you for the help.


Solution

  • You must remove the quotation marks around $categories otherwise you are searching in a string instead of your array.

    <ul>
        {foreach from=$categories item=category}
            <li>{$category.name}</li>
        {/foreach}
    </ul>
    

    Edit: You can also remove the quotation marks around category in item=category which is not needed, but recommended as a good practice.

    If you have any doubts you can also read Smarty docs here: https://www.smarty.net/