Eric
Eric

Reputation: 5091

django template tag on multiple line

I am creating a custom django template tag by using such a code :

@register.simple_tag(takes_context=True)
def render_listing(context, *args, **kwargs):
   ... my code ...

This works well, but in my template, it seems that all parameters must be on a single line, for example :

this works:

{% render_listing param1=val1 param2=val2 ... paramN=valN %}

but on multiple lines, it does not work :

{% render_listing param1=val1 
                  param2=val2 
                  ... 
                  paramN=valN %}

I tried multiple escape sequences but I did not succeeded,

Is there a way to specify a template tag on multiple lines ?

Upvotes: 32

Views: 13412

Answers (2)

Zach Snow
Zach Snow

Reputation: 1044

It's pretty straightforward to enable, though hackish:

import re
from django.template import base
base.tag_re = re.compile(base.tag_re.pattern, re.DOTALL)

"Using" it is simple; one place I find it especially useful is {% include %} tags:

{% include 'my/sweet/modal-template.template' with
    message="Hey, do you really want to frob the widget?"
    yes="Heck yes I do!"
    no="No frickin' way!"
    icon="error"
%}

I haven't tested this in more recent versions of Django but I imagine it could be adapted; that worked at least back around 1.8. I should point out that in theory some tags that do custom parsing of their arguments could break; in practice I haven't had any trouble in the last ~10 years of Django programming.

Upvotes: 20

Alasdair
Alasdair

Reputation: 308779

No, the Django template language does not support multiple line tags. See ticket 8652, which was closed as WONTFIX, or this thread from the django-developers mailing list.

Sometimes, if there is a repeated prefix, you can make it more readable by using the with tag. For example if you have,

{% render_listing param1=long.common.prefix.val1 param2=long.common.prefix.val2 param2=long.common.prefix.val3 %}

you could rewrite as

{% with prefix=long.common.prefix %}
{% render_listing param1=prefix.val1 param2=prefix.val2 param2=prefix.val3 %}
{% endwith %}

Often (but not always), a really long tag is an indication that you're putting too much logic in the template. See if you can move some of it into the view, model method, template tag or template filter.

Upvotes: 30

Related Questions