From 230499a9f28958367c89cf3c8a65d4c5c3689dc3 Mon Sep 17 00:00:00 2001 From: Armin Ronacher Date: Mon, 21 May 2007 23:12:59 +0200 Subject: [PATCH] [svn] added a snippet to the jinja docs for using django filters in jinja --HG-- branch : trunk --- docs/src/devrecipies.txt | 38 +++++++++++++++++++++++++++++++++++++- docs/src/filters.txt | 4 ++++ 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/docs/src/devrecipies.txt b/docs/src/devrecipies.txt index 7f5b6c0..b5dc098 100644 --- a/docs/src/devrecipies.txt +++ b/docs/src/devrecipies.txt @@ -4,7 +4,6 @@ Recipies For Developers Here some recipies for application developers. - Automagic Template Variables ============================ @@ -37,3 +36,40 @@ You can use it now like this: return env.autorender('foo.html') In the template you can now access the local variables `seq` and `foo`. + +Using Django Filters with Jinja +=============================== + +If you use Jinja in django and want to use some of the filters that +are part of the django core you can use this snippet: + +.. sourcecode:: python + + def convert_django_filter(f): + def filter_factory(*args): + def wrapped(env, ctx, value): + return f(value, *args) + return wrapped + return filter_factory + +You can now convert django filters for jinja using `convert_filter`. *Note*: +Django only supports one filter argument. Because of this limitation you +shouldn't pass it more arguments than it accepts. Because django uses some +introspection to find out if a filter accepts an argument weird things can +happen if you call it with an incompatible argument count. + +You can now register django filters for a jinja environment: + +.. sourcecode:: python + + from django.template.defaultfilters import date + env.filters['date'] = convert_django_filter(date) + +And use it: + +.. sourcecode:: jinja + + {{ entry.pub_date|date }} + +Also keep in mind that Jinja knows about keywords, thus you cannot have a filter +that is called `pluralize` for example. diff --git a/docs/src/filters.txt b/docs/src/filters.txt index b8881e0..b21781d 100644 --- a/docs/src/filters.txt +++ b/docs/src/filters.txt @@ -54,4 +54,8 @@ The wrapped function is created internally by the decorator, any positional arguments are forwarded to the filter function. The first argument is always the value already converted into a string. +If you're using Jinja with django and want to use the django filters in Jinja +have a look at the `developer recipies`_ page. + .. _designer documentation: builtins.txt +.. _developer recipies: devrecipies.txt -- 2.26.2