Login

Snippets by hasenj

Snippet List

Jinja2 integration + application specific functions/filters/tests

Jinja2 is an alternative template system that can be plugged into django. It offers greator flexibility in presentation logic; if you find the django template system too restrictive, you should have a look at Jinja2 (The syntax is very similar). In Jinja, you don't need costum tags (most of the time), because you can call functions and pass them parameters too! The only problem is that you cannot "load" functions from the template, this "loading" must be done by the code that renders the template. Same goes for filters and tests. If you need only two or three functions/filters, no problem, you can manually add them to the Environment object; but this method doesn't really scale with real-life webapps. This module/snippet offers a solution by allowing the user to define application-specific functions and filters and load them into the jinja2 environment automatically. Here's how to use this: 1. Install Jinja2 (for a quick & dirty installation, you can just put the jinja2 folder in a folder that's in PYTHONPATH) 2. Save this python module somewhere and call it something meaningful (I have it as jinja.py in my project directory) 3. Whenever you need to respond (an HttpResponse) with a template that's rendered by jinja, import this module and call `return jrespond( template_name, context )` 4. Any filters or functions you define in any of your applications will be readily available inside the template (see the documentation in code)

  • template
  • templates
  • jinja
  • template-tags
  • jinja2
Read More

hasenj has posted 1 snippet.