Passing variable to a macro in Jinja2

15,023

Solution 1

I believe

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

should work

Solution 2

Although Emmett J. Butler has provided an answer, there's a small nitpick with the ordering of macro parameters. You currently use following signature:

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

You should always put the arguments containing default value after all the other required arguments, therefore changing the order into this:

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

Now when calling macros with variables as arguments, you don't need to surround your variables with {{ }} because you are already inside the {% ... %}.

Share:
15,023
depecheSoul
Author by

depecheSoul

Updated on June 07, 2022

Comments

  • depecheSoul
    depecheSoul almost 2 years

    I have made some small macro that I am using to display text line and label for it:

    {% 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 %}
    

    The problem is when I call jinja2 macro:

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

    I can't get it to work when I call input with {{value_username}} as parameter, I always get an error.

    Do you know any solution how can I call {{value_username}} as parameter.

  • 正宗白布鞋
    正宗白布鞋 over 10 years
    Thanks, it works great even with filter. But, if there is other strings append or prepped to the variable, (for example => "Hello {{ value_username | capitalize }}, good morning!"), is it possible to pass this kind of string to macro? I'm trying to avoid make whole strings being a single variable, because there are many prepped and append combinations.