Alternatives to render_template
You can use render_template_string() as shown below if you need a quick test case that uses Jinja2 and Python (Flask) in the one file. However, best practise is to keep HTML template code separate.
injectingJinja2-1.py
from flask import * app = Flask(__name__) HTML = """ <h1>{{some_variable}}</h1> """ @app.route("/") def main(): return render_template_string(HTML, some_variable="memes") app.run(debug=True)
injectingJinja2-2.py
from flask import * app = Flask(__name__) HTML = """ <!doctype html> {% if some_variable == "microsoft" %} <h1 style="color:fuchsia;">we love microsoft!</h1> {% else %} <h1 style="color:teal;">we love apple!</h1> {% endif %} """ @app.route("/") def main(): return render_template_string(HTML, some_variable="apple") app.run(debug=True)
stringreader.py
from flask import * app = Flask(__name__) @app.route("/") def htmlFile(): html = "" with open(app.root_path + "/templatestring.html") as file: html = file.read() return html app.run()
templatestring.html
<!-- PUT THIS IN SAME LOCATION AS stringreader.py --> <!doctype html> <h1>template string</h1><br> <p>some random template garb</p> <!-- PUT THIS IN SAME LOCATION AS stringreader.py -->