英文:
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 -%}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论