Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing variable to a macro in Jinja2

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.

like image 262
depecheSoul Avatar asked Aug 28 '12 16:08

depecheSoul


People also ask

What is macros in Jinja2?

What are macros? Macros are similar to functions in many programming languages. We use them to encapsulate logic used to perform repeatable actions. Macros can take arguments or be used without them. Inside of macros we can use any of the Jinja features and constructs.

What is passing arguments to a macro?

A parameter can be either a simple string or a quoted string. It can be passed by using the standard method of putting variables into shared and profile pools (use VPUT in dialogs and VGET in initial macros). This method is best suited to parameters passed from one dialog to another, as in an edit macro.

How do you set a variable in Jinja?

How do you assign values in Jinja? {{ }} tells the template to print the value, this won't work in expressions like you're trying to do. Instead, use the {% set %} template tag and then assign the value the same way you would in normal python code.

How do you write an if statement in Jinja?

Jinja in-line conditionals are started with a curly brace and a % symbol, like {% if condition %} and closed with {% endif %} . You can optionally include both {% elif %} and {% else %} tags.


2 Answers

I believe

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

should work

like image 128
Emmett Butler Avatar answered Sep 18 '22 12:09

Emmett Butler


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

like image 36
plaes Avatar answered Sep 19 '22 12:09

plaes