【问题标题】:Passing variable to a macro in Jinja2将变量传递给 Jinja2 中的宏
【发布时间】:2012-08-28 16:49:09
【问题描述】:

我制作了一些小宏,用于显示文本行和标签:

{% macro input(name, text, help_text, value="", input_type) -%}
    <label for="id_{{name}}">{{text}}<span class="right">{{help_text}}</span></label>
    <input id="id_{{name}}" name="{{name}}" value="{{value}}" type="{{input_type}}" />
{{%- endmacro %}

问题是当我调用 jinja2 宏时:

{{input("username", "Korisničko ime:", "Pomoć", {{value_username}}, "text")}

当我使用{{value_username}} 作为参数调用输入时,我无法让它工作,我总是得到一个错误。

你知道任何解决方案我如何调用{{value_username}} 作为参数。

【问题讨论】:

    标签: python google-app-engine jinja2


    【解决方案1】:

    我相信

    {{ input("username", "Korisničko ime:", "Pomoć", value_username, "text") }}
    

    应该工作

    【讨论】:

    • 谢谢,即使使用过滤器也能很好地工作。但是,如果有其他字符串附加或准备到变量中,(例如 =>“Hello {{ value_username | capitalize }},早上好!”),是否可以将这种字符串传递给宏?我试图避免使整个字符串成为单个变量,因为有许多 prepped 和 append 组合。
    【解决方案2】:

    虽然 Emmett J. Butler 提供了一个答案,但在宏参数的排序方面还是存在一些小问题。您目前使用以下签名:

    input(name, text, help_text, value="", input_type)
    

    您应该始终将包含默认值的参数放在所有其他必需参数之后,因此将顺序更改为:

    input(name, text, help_text, input_type, value="")
    

    现在,当使用变量作为参数调用宏时,您不需要用 {{ }} 包围变量,因为您已经在 {% ... %} 中。

    【讨论】:

      猜你喜欢
      • 2021-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-29
      • 1970-01-01
      • 2019-12-06
      • 1970-01-01
      • 2018-06-07
      相关资源
      最近更新 更多