Synal
Synal

Reputation: 85

How to pass parameters to a jinja2 flask function call?

I am trying to pass a parameter to a context_processor function.

@app.context_processor
    def my_utility_processor():
        def foo(var):
            return var
    return dict(foo=foo)

The jinja/html template part looks like that:

    <button type="button" class="btn btn-info" onclick="var name={{ i.DeviceName }};this.disabled=true;alert('{{ foo({{ variable }}) }} ')">
Click</button>

Is it somehow possible to pass a jinja2 parameter to a jinja function call?

Upvotes: 3

Views: 9090

Answers (2)

Juh_
Juh_

Reputation: 15539

From what I read here: https://sopython.com/canon/103/use-jinja-variable-in-function-call/

"Don’t nest curly braces within a Jinja expression, you’re already in the expression"

So for your case, you should simply write:

alert('{{ foo(variable) }}')

(Note: I didn't try it yet)

Upvotes: 0

dirn
dirn

Reputation: 20729

Once you enter a {{ ... }} block you are governed by Python's syntax.

alert('{{ foo(variable) }} ')"

Depending on the output of foo, though, this could cause a JavaScript error. You can go one step further and make Jinja format the output for you

alert({{ foo(variable)|tojson|safe }})

This will take care of things like quoting strings for you.

Upvotes: 2

Related Questions