pallets / jinja

A very fast and expressive template engine.
https://jinja.palletsprojects.com
BSD 3-Clause "New" or "Revised" License
10.28k stars 1.61k forks source link

filters.map: apply filter to attribute ("mapattr") #1950

Open VannTen opened 6 months ago

VannTen commented 6 months ago

Hello,

Could the map filter be able to combine both of its functionality, and apply a filter to an attribute before returning the whole structure ?

I'm often trying to use map in the following manner: data | map(attribute='sub.key', 'somefilter', filter_args) With data being:

data:
- key1: value
  key2: value
  sub:
    key: some_value
- key1: value
  key2: value
  sub:
    key: some_value

and expecting the result of 'somefilter' in sub.key in each element of the newly produced array.

I haven't found an easy way to achieve this with existing filters (but I might have missed something).

Obviously, this can be implemented in an extension, (I'd call that mapattr, I guess ?), but since this would be backward compatible with map (it would merely transform what is now an invalid call into a valid one : map(attribute='someattr', 'somefilter')

What do you think ? If the jinja project deems this a good idea, I can do the PR.