Created
October 24, 2011 17:02
-
-
Save rduplain/1309522 to your computer and use it in GitHub Desktop.
Template helpers vs global context processing in Flask.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Discussing Flask templating with Hazel|work on #pocoo. | |
# Mixing request args and view func args in a template. | |
# Re: http://pastebin.com/Jr8ZUb25 | |
from flask import Flask, request, render_template | |
app = Flask(__name__) | |
def get_endpoint_args(request): | |
"Given a Flask request, return combination of request & view func args." | |
endpoint_args = dict() | |
if request.view_args: | |
endpoint_args.update(request.view_args) | |
if request.args: | |
endpoint_args.update(request.args) | |
return endpoint_args | |
@app.context_processor | |
def add_template_helpers(): | |
# You could simply inject the result of get_endpoint_args. | |
# But in my experience, it's easier to read templates which use functions | |
# and filters than to inject variables into the global context. | |
# | |
# This is especially important for helper functions or context variables | |
# which require a lot of work, as the context processor is run on each call | |
# to render_template. | |
return dict(get_endpoint_args=get_endpoint_args) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment