[Python] Jinja2, Using map with format filter, what is the trick?

Discussão em 'Python' iniciado por Stack, Março 3, 2025.

  1. Stack

    Stack Membro Participativo

    New comer in Jinja2, I'm fan of map feature to play with list. So my intention is to use map filter to format a python list. I read Jinja2 documentation that map filter can be use to "Applies a filter on a sequence of objects". But I don't find a clear way to pass a parameter to format filter when its use inside map filter in Jinja2 template

    example: python data:

    colors = [ 'blue', 'red', 'green']


    Jinja2 template (just reformat python list into scheme style) wanted result is colors=(list "blue" "red" "green")

    So I start with following template line but its not obvious where to place the format parameter '"%s"', the first parameter of map is the filter name only...

    colors=(list {{ colors | map('format') | join(" ")}})


    I read some workaround some of you

    • use ansible filter regexp-replace to do the job
    • other use for structure in Jinja2 template

    {% for color in colors %} "{{color}}" {% endfor %}

    But I just need to know if I miss something to do that with map and format filter ?

    Thanks by advance for your answer regards

    For Information, I use python 3.6.3 and Jinja2 3.0.1

    Continue reading...

Compartilhe esta Página