【问题标题】:Add quotes around each string in a list in jinja2?在 jinja2 的列表中为每个字符串添加引号?
【发布时间】:2013-03-09 00:07:49
【问题描述】:

Python中的变量:

names = ["a", "b"]

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

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

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

c(a, b)

然而,我真正需要的是:

c("a", "b")

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

【问题讨论】:

  • 为什么需要这样做?如果这是 JavaScript 代码,你考虑过 JSONP 吗?
  • @Blender 这是 R 代码..

标签: python template-engine jinja2


【解决方案1】:

为 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

【讨论】:

  • 您可能希望使用[repr(a) for a in a_list] 正确转义包含He said "Hello" 等特殊字符的项目`
【解决方案2】:
# some.py file
names = ['a', 'b', 'c']

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

# renders as the following, brackets included
['a', 'b', 'c']

【讨论】:

    【解决方案3】:

    在 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}
    

    【讨论】:

      猜你喜欢
      • 2018-05-17
      • 1970-01-01
      • 2012-08-14
      • 1970-01-01
      • 2018-11-28
      • 2011-10-08
      • 2018-01-05
      • 2022-01-22
      • 2021-11-11
      相关资源
      最近更新 更多