如何执行一个不返回输出且不赋值给变量的自定义过滤器?

huangapple go评论103阅读模式
英文:

How do I execute a custom filter that returns no output without assigning to a variable?

问题

{%- set unused = {'one': 'aaa', "two": "bbb", 'three': 'ccc'} | get_env_var -%}
英文:

I have a custom filter that updates a global variable in my code and does some other stuff when called. It returns no output.

I just want to call it inside a template without assigning the output to a variable.

Doing this works but I want to remove the unnecessary variable assignment:

{%- set unused = {'one': 'aaa', "two": "bbb", 'three': 'ccc'} | get_env_var -%}

I've tried the following:

{%- {'one': 'aaa', "two": "bbb", 'three': 'ccc'} | get_env_var -%}
jinja2.exceptions.TemplateSyntaxError: tag name expected
{{'one': 'aaa', "two": "bbb", 'three': 'ccc'} | get_env_var}
jinja2.exceptions.TemplateSyntaxError: expected token 'end of print statement', got ':'
{{{'one': 'aaa', "two": "bbb", 'three': 'ccc'} | get_env_var}}
yaml.composer.ComposerError: expected a single document in the stream
in "<unicode string>", line 3, column 1:
    ccc
    ^
but found another document
  in "<unicode string>", line 4, column 1:
    ---
    ^

How do I just execute a custom filter and not capture its output?

答案1

得分: 1

鉴于您的环境已经启用了 expression statement extension,那么表达式语句 — {% do ... %} — 是您用例的最佳选择。

正如文档中指出的,它的作用类似于变量表达式 — {{ ... }} — 但不会输出任何内容。

在您的情况下,使用方式应该是这样的:

{%- do {
    'one': 'aaa',
    'two': 'bbb',
    'three': 'ccc'
} | get_env_var -%}
英文:

Given that your environment already have the expression statement extension enabled, then the expression statement — {% do ... %} — is the best fit for your use case.

As pointed in the documentation, it acts like a variable expression — {{ ... }} — but won't print anything.

The usage in your case would be something like:

{%- do {
    'one': 'aaa', 
    'two': 'bbb', 
    'three': 'ccc'
} | get_env_var -%}

huangapple
  • 本文由 发表于 2023年4月17日 22:21:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76036172.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定