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:
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].