Python中的变量:
names = ["a", "b"]
我目前在Jinja2模板中写的内容:
c({{ names | join(",") }})
我使用上面的模板获得了什么:
c(a, b)
然而,我真正需要的是:
c("a", "b")
我检查了Jinja2的文档,但没有找到过滤器来执行此操作。有没有人在Jinja2中有这个想法?
答案 0 :(得分:8)
为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
答案 1 :(得分:0)
# some.py file
names = ['a', 'b', 'c']
# some.html file
{{ names|safe }}
# renders as the following, brackets included
['a', 'b', 'c']
答案 2 :(得分:0)
在ansible中用作filter_plugin并传递pylint:
''' From https://stackoverflow.com/a/68610557/571517 '''
class FilterModule():
''' FilterModule class must have a method named filters '''
@staticmethod
def surround_by_quotes(a_list):
''' implements surround_by_quotes for each list element '''
return ['"%s"' % an_element for an_element in a_list]
def filters(self):
''' returns a dictionary that maps filter names to
callables implementing the filter '''
return {'surround_by_quotes': self.surround_by_quotes}