pythontemplate-enginejinja2

Add quotes around each string in a list in jinja2?


The variable in Python :

names = ["a", "b"]

What I write currently in Jinja2 template:

c({{ names | join(",") }})

What I get using the template above:

c(a, b)

However, what I really need is:

c("a", "b")

I checked the document of Jinja2 but doesn't find a filter to do this. Does anyone have ideas about this in Jinja2?


Solution

  • Use custom filters for jinja2:

    def surround_by_quote(a_list):
        return ['"%s"' % an_element for an_element in a_list]
    
    env.filters["surround_by_quote"] = surround_by_quote