Skip to content

Instantly share code, notes, and snippets.

@bacher09
Created November 11, 2013 11:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bacher09/7411829 to your computer and use it in GitHub Desktop.
Save bacher09/7411829 to your computer and use it in GitHub Desktop.
Example of template_global in flask < 0.10
from flask import Flask, render_template_string
MAIN_TEMPLATE = """ \
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>{{ message }}</title>
</head>
<body>
<p>Message: {{ message }}</p>
{{ top_articles() }}
</body>
</html>"""
ARTICLES_TEMPLATE = """ \
<ul>
{% for article in articles -%}
<li>{{ article }}</li>
{%- endfor %}
</ul>"""
def top_articles():
# load articles from db ;)
articles = [
"First article",
"Second article",
"Third article"
]
return render_template_string(ARTICLES_TEMPLATE, articles=articles)
app = Flask(__name__)
app.config["DEBUG"] = True
app.jinja_env.globals["top_articles"] = top_articles
@app.route("/")
def page():
return render_template_string(MAIN_TEMPLATE, message="Hello World")
if __name__ == "__main__":
app.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment