How to rewrite the initial array and remove items by the ID in the view with Smarty?

Asked

Viewed 68 times

1

I’m using the View rendering library with Smarty.

In my view, I have an output with the product information array inside a foreach:

{assign var='remove_products' [712, 716, 717, 718, 719, 720, 745, 755, 758]}
  {foreach from=$products item=product name=products}
    {if !in_array($product.id_product, $remove_products)}
        {$product.id_product|escape:'htmlall':'UTF-8'}
        {$product.name|escape:'htmlall':'UTF-8'}
        {$product.legend|escape:'htmlall':'UTF-8'}
        <!-- OBS: gostaria de salvar todos os dados acima
                em um novo array e usar a coleção novamente abaixo
        -->
    {/if}
  {/foreach]}  

 <!-- usando a coleção (nova) só que com os itens removidos -->

 {$products}     

How could I do that. Does anyone know? I tried to do this but it didn’t roll:

   {assign var='remove_products' [712, 716, 717, 718, 719, 720, 745, 755, 758]}
    {assign var='n_products' []}
    {foreach $products as $key => $value}
        {if !in_array($value.id_product, $remove_products)}
            {$n_products[$key] = $value}   
        {/if}
    {/foreach}
    {$products = $n_products}
  • Which is Marty? The first example has the face of 2, the other of 3. You really need to define the array within the view/template?

  • The first one I’m wearing.

  • 1

    The same is true to avoid having business rules directly in the views. You cannot pass the vector of products treated from the controller?

  • I agree, only the system will be migrated soon, I need to rewrite it now, just to solve a little problem.

2 answers

1

If you are actually using Smarty 2, there is no cool way to do this, you need to do what you should not, which is to use the php tag within the template.

{php} 
    $this->assign("remove_products", array(712, 716, 717, 718, 719, 720, 745, 755, 758)); 
{/php}

Based on: How to assign an array Within a Smarty template file?

0

I managed to solve the problem by doing so:

 {if isset($products)}
    {assign var='remove_products' [712, 716, 717, 718, 719, 720, 745, 755, 758]}
    {assign var='n_products' []}
    {foreach from=$products key=key item=product name=products}
       {if !in_array($product.id_product, $remove_products)}
           {$n_products[$key] = $product}
       {/if}
    {/foreach}
 {$products = $n_products}
{/if}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.