Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 693
Brandon Avatar asked Dec 15 '22 21:12

Brandon


2 Answers

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.

like image 122
Rachel Sanders Avatar answered Dec 17 '22 09:12

Rachel Sanders


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.

like image 24
Lovato Avatar answered Dec 17 '22 10:12

Lovato