How to remove duplicated items in array on Twig

后端 未结 7 1042
-上瘾入骨i
-上瘾入骨i 2020-12-14 06:40

How to remove duplicated items in array on Twig?

I have array value in twig such as.

{{ set array = [\"testA         


        
相关标签:
7条回答
  • 2020-12-14 07:22

    Quick Answer (TL;DR)

    • A custom Twig filter array_unique permits removal of duplicates
    • This can be directly carried over from native PHP

    Detailed Answer

    Context

    • Twig 2.x (latest version as of Wed 2017-02-08)
    • Alternate approach in comparison to other approaches specified elsewhere

    Problem

    • Scenario:
    • DeloperSutasSugas wishes to dedupe an array
    • PHP built-in array_unique function can do the job

    Example01

    • DeloperSutasSugas starts with a sequentially-indexed array
    • transform from BEFORE into AFTER
    {%- set mylist = ['alpha','alpha','bravo','charlie','alpha','alpha','delta','echo']  -%}
    
    BEFORE: 
    ['alpha','alpha','bravo','charlie','alpha','alpha','delta','echo']
    
    AFTER: 
    ['alpha','bravo','charlie','delta','echo']
    
    

    Solution

    Custom filter
    [...]
    // {"define_filter_":"array_unique" ,"desc":"PHP array_unique function" },
    $filter = new Twig_SimpleFilter('array_unique', function ( $vinp=Array() ) {
      $vout = ( $vinp );
      $vout = array_unique( $vout );
      $vout = array_values( $vout ); // PHP annoyance array reindex -- optional
      return $vout;
    });
    $twig->addFilter($filter);
    //;;
    [...]
    
    Output
    {%- set mylist = mylist|array_unique  -%}    
    

    Pitfalls

    • Requires addon filter (the solution does not work with native Twig)

    See also

    • https://twigfiddle.com/rsl89m
    0 讨论(0)
  • 2020-12-14 07:23

    The in operator performs containment test.

    It returns true if the left operand is contained in the right.

    {% if name in array %}
    

    http://twig.sensiolabs.org/doc/templates.html#containment-operator

    0 讨论(0)
  • 2020-12-14 07:26

    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') %}
    
    0 讨论(0)
  • 2020-12-14 07:37
    {% set keeper = {} %}
    {% set throwaway = [] %}
    {% for thing in yourSet.all() %}
    
      {% if thing.id not in throwaway %}
        {% set throwaway = throwaway|merge([thing.id]) %}
        {% set keeper = keeper|merge([{ slug: thing.slug, title: thing.title}]) %}
      {% endif %}
    
    {% endfor %}
    

    Modification on the accepted answer above. I needed to remove duplicates from a set and end up with an object of just slug and title.

    0 讨论(0)
  • 2020-12-14 07:40

    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 %}
    
    0 讨论(0)
  • 2020-12-14 07:45

    You can do it in one line since Twig 1.41 and 2.10:

    {% set unique = array|reduce(
        (unique, item) => item in unique ? unique : unique|merge([item]), []
    ) %}
    

    In your example:

    {% for name in array|reduce((unique, item) => item in unique ? unique : unique|merge([item]), []) %}
         My name is {{name}}
    {% endfor %}
    
    0 讨论(0)
提交回复
热议问题