Brandon
Brandon

Reputation: 3891

Printing Variables in a Flask Template

I have a variable in my code that is buried deep in some legacy code. Rather than spend all day searching for it, I'd like to just print out the variable from within the jinja template. Is that possible?

I tried {% print var %}, but that didn't seem to do anything.

Upvotes: 4

Views: 19556

Answers (2)

Lovato
Lovato

Reputation: 2310

You need context-processors.

Example to put on your .py file:

@app.context_processor
def get_legacy_var():
    return dict(get_legacy_var=your_get_legacy_var_function())

Then on your template:

{{ get_legacy_var }}

This will call Python during template generation, will get the value for your variable, and return it to the template.

Upvotes: 2

Rachel Sanders
Rachel Sanders

Reputation: 5874

The syntax for outputting variables is {{var}}, {% %} is for blocks and other directives. However, it sounds like the variable wasn't passed to the template. Check for that.

If you're doing a lot of debugging, try Flask-DebugToolbar, it'll print out all the variables that got passed to your template so you don't have to muck around with print statements like this. Useful stuff.

Upvotes: 10

Related Questions