From 450756b9b93bc9b1a28c84b07289e4db3454c907 Mon Sep 17 00:00:00 2001 From: Armin Ronacher Date: Sun, 15 Apr 2007 15:13:59 +0200 Subject: [PATCH] [svn] added `xmlattr` filter to jinja --HG-- branch : trunk --- CHANGES | 2 +- jinja/filters.py | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/CHANGES b/CHANGES index 2d34821..08b316f 100644 --- a/CHANGES +++ b/CHANGES @@ -44,7 +44,7 @@ Version 1.1 - added `sum`, `abs` and `round` filters. This fixes #238 -- added `striptags` filter. +- added `striptags` and `xmlattr` filters for easier SGML/XML processing Version 1.0 diff --git a/jinja/filters.py b/jinja/filters.py index a6d0dd8..6af5cec 100644 --- a/jinja/filters.py +++ b/jinja/filters.py @@ -118,6 +118,42 @@ def do_escape(attribute=False): return wrapped +def do_xmlattr(): + """ + Create an SGML/XML attribute string based on the items in a dict. + All values that are neither `none` nor `undefined` are automatically + escaped: + + .. sourcecode:: html + + + ... + + + Results in something like this: + + + + *New in Jinja 1.1* + """ + e = escape + def wrapped(env, context, d): + if not hasattr(d, 'iteritems'): + raise TypeError('a dict is required') + result = [] + for key, value in d.iteritems(): + if value not in (None, Undefined): + result.append(u'%s="%s"' % ( + e(env.to_unicode(key)), + e(env.to_unicode(value), True) + )) + return u' '.join(result) + return wrapped + + def do_capitalize(s): """ Capitalize a value. The first character will be uppercase, all others @@ -772,6 +808,7 @@ FILTERS = { 'lower': do_lower, 'escape': do_escape, 'e': do_escape, + 'xmlattr': do_xmlattr, 'capitalize': do_capitalize, 'title': do_title, 'default': do_default, -- 2.26.2