8

Python中的变量:

names = ["a", "b"]

我目前在 Jinja2 模板中写的内容:

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

我使用上面的模板得到了什么:

c(a, b)

但是,我真正需要的是:

c("a", "b")

我检查了 Jinja2 的文档,但没有找到执行此操作的过滤器。有人在 Jinja2 中对此有任何想法吗?

4

3 回答 3

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
于 2013-03-20T05:19:10.513 回答
0
# some.py file
names = ['a', 'b', 'c']

# some.html file
{{ names|safe }}

# renders as the following, brackets included
['a', 'b', 'c']
于 2015-03-22T17:58:23.737 回答
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}
于 2021-08-01T12:46:49.893 回答