Django Template Tag vs Kay Framework Processors
Posted 6 days, 18 hours ago
In our previous post we discovered how to obtain in Kay templates the same behavior as Django's inclusion tag. Another question pops in. What about template tags?
What is a template tag?
"A template tag is code that displays information dynamically in the template."
In other words, it's a method that handles the data based on the context and outputs it in the desired manner. The Django docs example is pretty clear:
- <p>The time is {% current_time "%Y-%m-%d %I:%M %p" %}.</p>
- #output
- The time is 2010-09-03 11:13 PM
Kay framework doesn't allow you do import .py files to use their functions inside a template, because it's not transforming it in a list of nodes, like Django does.
CONTEXT_PROCESSORS
"Much like Django’s context processors Kay allows you to define a
number of functions that are run when templates are rendered that
make commonly used data available to your template."
This is exactly what we have been searching for. Let's see how to define such a context processor and how to use it in a template for the Django example:
- # my_app.utils - defining the method
- import datetime
- def current_time(format_string = "%Y-%m-%d %I:%M %p")
- return datetim.datetime.now().strftime(format_string)
- # my_app.context_processors - create the processor
- from utils import current_time
- def current_time_processor(request):
- return {'current_time': current_time}
- # settings - include the processor
- CONTEXT_PROCESSORS = (
- ...
- 'my_app.context_processors.current_time_processor'
- )
- # template usage
- <p>The time is {{ current_time("%Y-%m-%d %I:%M %p") }}.</p>
- # output
- The time is 2010-09-03 11:13 PM
Applying processors for single view, not for the whole project
If the processor will only be used in a few templates, you can skip the part where we include it in the settings.CONTEXT_PROCESSORS tuple and send it when rendering the view's response:
- # my_app.views
- from kay.utils import render_to_response
- from context_processors import current_time_processor
- def current_time(request):
- return render_to_response('my_app/current_time.html', {}, processors=(current_time_processor,))
The only functionality that is missing is setting a variable in the context and there doesn't seem to be a solution for it.
Note: The returned value of your function will need the |safe filter applied to it to avoid HTML escaping.
Categories: GAE Kay Framework
Leave a Comment







