【问题标题】:Include and exclude string output when rendering jinja2 template via filtering通过过滤渲染 jinja2 模板时包含和排除字符串输出
【发布时间】:2020-10-10 04:54:36
【问题描述】:

我正在尝试构建一个模板来支持特定控制台平台的配置行。

运行配置格式如下:

示例 1:

/settings/network_connections/ETH0/ipv4_mode=static
/settings/network_connections/ETH0/pv4_address=10.0.0.10
/settings/network_connections/ETH0/ipv4_bitmask=24 
/settings/network_connections/ETH0/ipv4_gateway=10.0.0.1

如果你想配置以下这些行,它前面加上“set”这个词,如下所示:

示例 2:

set /settings/network_connections/ETH0/ipv4_mode=static
set /settings/network_connections/ETH0/pv4_address=10.0.0.10
set /settings/network_connections/ETH0/ipv4_bitmask=24 
set /settings/network_connections/ETH0/ipv4_gateway=10.0.0.1

在我的 jinja2 模板中,我有这样的内容:

示例 3

{{ set| remediation }} /settings/network_connections/ETH0/ipv4_mode=static
{{ set| remediation }} /settings/network_connections/ETH0/pv4_address=10.0.0.10
{{ set| remediation }} /settings/network_connections/ETH0/ipv4_bitmask=24
{{ set| remediation }} /settings/network_connections/ETH0/ipv4_gateway=10.0.0.1

我希望能够渲染模板并能够输出示例 2 中的内容(使用“set”),以及使用布尔变量( with_remediation)。如果为真,则包括“设置” - 否则排除“设置”。在示例 3 中,“补救”是一个嵌入式自定义过滤器。

import jinja2

loader = jinja2.FileSystemLoader('/tmp')
env = jinja2.Environment(autoescape=True, loader=loader)

def remediation(input,with_remediation):
    """Custom filter"""
    if(with_remediation):
        return input
    else:
        return ""

env.filters['remediation'] = remediation
temp = env.get_template('template.jinja2')
temp.render(set="set")

但我不确定如何将变量 'with_remediation' 传递给函数 remediate。

我已尝试按照答案中提供的示例Embed custom filter definition into jinja2 template? 进行操作,但不确定它是否有助于我想要实现的目标。

另外,我怎样才能将它编码为“set”可以是我想要的任何“字符串”?我必须在temp.render(set="set") 行中包含我想使用的每个字符串吗?例如; temp.render(set="set", delete="delete",rename="rename") 或者是否有更有效的方法来解决这个问题?

【问题讨论】:

    标签: python jinja2


    【解决方案1】:

    我可以通过这样做来解决它;通过将 with_remediation 设置为 True 来输出“设置”;通过将 with_remediation 设置为 False 来排除输出“设置”:

    import jinja2
    
    loader = jinja2.FileSystemLoader('/tmp')
    env = jinja2.Environment(autoescape=True, loader=loader)
    
    with_remediation = True
    
    def remediation(input):
        """Custom filter"""
        if(with_remediation):
            return input
        else:
            return ''
    
    env.filters['remediation'] = remediation
    temp = env.get_template('template.jinja2')
    temp.render(set='set')
    

    模板:

    {{ set | remediation }}/settings/network_connections/ETH0/ipv4_mode=static
    {{ set | remediation }}/settings/network_connections/ETH0/pv4_address=10.0.0.10
    {{ set | remediation }}/settings/network_connections/ETH0/ipv4_bitmask=24
    {{ set | remediation }}/settings/network_connections/ETH0/ipv4_gateway=10.0.0.1
    

    【讨论】:

      猜你喜欢
      • 2015-01-06
      • 2013-08-11
      • 2018-07-29
      • 2018-08-19
      • 1970-01-01
      • 2015-09-08
      • 2012-02-03
      • 2021-02-19
      • 1970-01-01
      相关资源
      最近更新 更多