Hi I've been trying to create an extension for jinja2 that would join multiple items with a separator, while skipping items (template fragments) that evaluate to whitespace.
There are several of those fragments and you never know in advance which ones will be non-empty and which ones will.
Sounds like a trivial task, but I had real hard time making this to work in jinja2. Maybe part of the reason is that jinja does not allow to define custom template nodes.
Would you have any suggestions? Below is a snippet that will do the parsing job, but it's missing the evaluation part.
class JoinerExtension(Extension):
"""Template tag that joins non-whitespace (string) items
with a specified separator
Usage syntax:
{% joinitems separator='|' %}
....
{% separator %}
....
{% separator %}
....
{% endjoinitems %}
where value of "separator" within the joinitems tag
can be an expression, not necessarily a sting
"""
tags = set(['joinitems'])
def parse(self, parser):
"""parse function for the
joinitems template tag
"""
lineno = next(parser.stream).lineno
#1) read separator
separator = None
while parser.stream.current.type != 'block_end':
name = parser.stream.expect('name')
if name.value != 'separator':
parser.fail('found %r, "separator" expected' %
name.value, name.lineno,
exc=TemplateAssertionError)
# expressions
if parser.stream.current.type == 'assign':
next(parser.stream)
separator = parser.parse_expression()
else:
var = parser.stream.current
parser.fail('assignment expected after the separator' %
var.value, var.lineno,
exc=TemplateAssertionError)
#2) read the items
items = list()
end_tags = ['name:separator', 'name:endjoinitems']
while True:
item = parser.parse_statements(end_tags)
items.append(item)
if parser.stream.current.test('name:separator'):
next(parser.stream)
else:
next(parser.stream)
break