Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unique filter does not seems to apply on concatenated list

I have two lists that I want to concatenate and then filter for unique values only. I figured this should be possible in Jinja2 using the unique filter, but, I’m finding it doesn’t work the way I expected. I’ve used a few different live Jinja parsers to test and they all seem to end up with incorrect output.

For reference, the site I’m using to test my code is https://j2live.ttl255.com/

With an input of data that looks like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

this:
  - one
  - one
that:
  - one
  - two

And a template that looks like this:

{{ this + that | unique | list }}

The rendered output is just the result of concatenating the two lists, when they clearly have duplicate values:

['one', 'one', 'one', 'two']

I’ve tried a bunch of different permutations here and they all end up the same way. Does anyone know how to get this to work as expected? Or am I missing something here? With the intent of the filter, I figured this would work.

I also want to point out, that the expected behaviour does occur when the lists are not concatenated. For example:

{{ this | unique | list }}

Results in:

['one']

>Solution :

The precedence is taken by the filter over the union of the two list.
What your code is effectively doing is:

{{ this + (that | unique | list) }}

So, what you really want to do is for the union to happen first, which you can do by using parenthesis:

{{ (this + that) | unique | list }}

Which results in your expected:

['one', 'two']

This is backed up by this comment on their issue tracker:

Filters and tests have higher precedence than binary operators. For example {{ [3] + [2,1] | sort }} yields [3, 1, 2], not [1, 2, 3].

As commented by ngaya-ll

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading