Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove duplicated items in array on Twig

Tags:

twig

How to remove duplicated items in array on Twig?

I have array value in twig such as.

{{ set array = ["testA","testB","testA","testC","testB"]  }} 

I want to remove duplicated items and use only testA,testB,testC

{% for name in array%}   //skip the duplicate items and use only testA,testB,testC  {% endfor %} 

How can I make it ?

like image 372
whitebear Avatar asked Jul 22 '13 13:07

whitebear


2 Answers

Twig is a VIEW engine, and should not be used - in theory - to manipulate data. It's a (very) good practice to use (assumingly) PHP to gather data, do all necessary manipulations and then pass the right data to your view.

That said, here's how you can do it in pure Twig syntax:

{% set newArray = [] %}  {% for name in array %}    {% if name not in newArray %}      My name is {{name}}    {% set newArray = newArray|merge([name]) %}    {% endif %}   {% endfor %} 
like image 80
Webberig Avatar answered Sep 18 '22 13:09

Webberig


In this case, as @Webberig said it's better to prepare your data before the rendering of the view. But when you have a more complex process and if is related to the view you can create a Twig Extension, with an extension the code would look like:

MyTwigExtension.php for Twig versions 1.12 and greater:

/**  * {@inheritdoc}  */ public function getFunctions() {     return array(         new \Twig_SimpleFunction('array_unset', array($this, 'arrayUnset'))     ); } 

If you are on a Twig version earlier than 1.12, use this MyTwigExtension.php instead:

/**  * {@inheritdoc}  */ public function getFunctions() {     return array(         'array_unset' => new \Twig_Function_Method($this, 'arrayUnset')     ); } 
/**  * Delete a key of an array  *  * @param array  $array Source array  * @param string $key   The key to remove  *  * @return array  */ public function arrayUnset($array, $key) {     unset($array[$key]);      return $array; } 

Twig:

{% set query = array_unset(query, 'array_key') %} 
like image 26
COil Avatar answered Sep 18 '22 13:09

COil