Home » Odeon Blogs » Liviu, Agile Bear »

Django Template Tag vs Kay Framework Processors

Django Template Tag vs Kay Framework Processors

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:

  1. <p>The time is {% current_time "%Y-%m-%d %I:%M %p" %}.</p>
  2. #output
  3. 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:

  1. # my_app.utils - defining the method
  2. import datetime
  3. def current_time(format_string = "%Y-%m-%d %I:%M %p")
  4. return datetim.datetime.now().strftime(format_string)
  5. # my_app.context_processors - create the processor
  6. from utils import current_time
  7. def current_time_processor(request):
  8. return {'current_time': current_time}
  9. # settings - include the processor
  10. CONTEXT_PROCESSORS = (
  11. ...
  12. 'my_app.context_processors.current_time_processor'
  13. )
  14. # template usage
  15. <p>The time is {{ current_time("%Y-%m-%d %I:%M %p") }}.</p>
  16. # output
  17. 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:

  1. # my_app.views
  2. from kay.utils import render_to_response
  3. from context_processors import current_time_processor
  4. def current_time(request):
  5. 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


Tagged as: context_processor django kay framework template tag



Leave a Comment :

(required)


(required)




(required)




(required)






Leave a Comment


Page generated in: 0.14s