Jinja: How to apply "format" on a list of strings?

Created on 16 Feb 2016  路  4Comments  路  Source: pallets/jinja

I try to do something like in Python

("db.%s.dump" % n for n in names)

I tried

{{ databases | map("format", "db.%s.dump") }}
{{ "db.%s.dump" | map("format", databases) }}

and a lot more. All I tried failed.

The documentation is of no help :-(

Most helpful comment

@NormanDenayer it's fine unless you want to pass it to another filter in map().

All 4 comments

why not {% for n in names %} {{ "db.%s.dump"|format(n) }} {% endfor %}?

@NormanDenayer it's fine unless you want to pass it to another filter in map().

Personally I ended with writing own plugin:

from jinja2.utils import soft_unicode

def format_string(text, fmt, *kw):
    return soft_unicode(fmt).format(text, *kw)

class FilterModule(object):
    def filters(self):
        return dict(format_string=format_string)

Usage:

list_of_names | map('format_string', 'hello {}!')

See https://github.com/pallets/jinja/pull/906#issuecomment-548393215 for why I'm declining this. It also contains a filter that could accomplish this, or you can write a more specific filter as shown above.

Was this page helpful?
0 / 5 - 0 ratings