Skip to content
Myr

Added @templated decorator to the patterns.

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Armin Ronacher · committed by Armin Ronacher · parent 8d49440 · Browse files · 1 file+49 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+49 added−0 removed

  • other:+49 added−0 removed

1 file+49 added−0 removed

modified:docs/patterns/viewdecorators.rst+49 added
89 unmodified lines
90 return decorator9192Notice that this assumes an instanciated `cache` object is available, see93:ref:`caching-pattern` for more information.949596Templating Decorator97--------------------9899A common pattern invented by the TurboGears guys a while back is a100templating decorator. The idea of that decorator is that you return a101dictionary with the values passed to the template from the view function102and the template is automatically rendered. With that, the following103three examples do exactly the same::104105 @app.route('/')106 def index():107 return render_template('index.html', value=42)108109 @app.route('/')110 @templated('index.html')111 def index():112 return dict(value=42)113114 @app.route('/')115 @templated()116 def index():117 return dict(value=42)118119As you can see, if no template name is provided it will use the endpoint120of the URL map + ``'.html'``. Otherwise the provided template name is121used. When the decorated function returns, the dictionary returned is122passed to the template rendering function. If `None` is returned, an123empty dictionary is assumed.124125Here the code for that decorator::126127 from functools import wraps128 from flask import request129130 def templated(template=None):131 def decorator(f):132 @wraps(f)133 def decorated_function(*args, **kwargs):134 template_name = template135 if template_name is None:136 template_name = request.endpoint + '.html'137 ctx = f(*args, **kwargs)138 if ctx is None:139 ctx = {}140 return render_template(template_name, **ctx)141 return decorated_function142 return decorator