Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django template passing a template variable into cut filter

I am trying to pass a template into a cut filter, something like this

{{ myVariable|cut:"something + templateVariable" }}

I've tried:

{{ myVariable|cut:"something"|add:templateVariable }}

and

{{ myVariable|cut:"something {{ templateVariable }}" }}

but these does not work.

Is this possible to do?

like image 472
zentenk Avatar asked Mar 20 '12 16:03

zentenk


People also ask

What is a more efficient way to pass variables from template to view in Django?

POST form (your current approach) This answer is perfect and I learned a great deal!

How do I inherit a template in Django?

extends tag is used for inheritance of templates in django. One needs to repeat the same code again and again. Using extends we can inherit templates as well as variables.

What does {{ name }} mean in Django templates?

What does {{ name }} this mean in Django Templates? {{ name }} will be the output. It will be displayed as name in HTML. The name will be replaced with values of Python variable.


1 Answers

It should work with a temporary variable using the with tag:

{% with myFilter="something"|add:templateVariable %}
    {{ myVariable|cut:myFilter }}
{% endwith %}

Or in Django 1.2 and older:

{% with "something"|add:templateVariable as myFilter %}
    {{ myVariable|cut:myFilter }}
{% endwith %}

Add does not support concatenation of string and int but you could easily make a template filter that converts to string for example:

from django import template

register = template.Library()

@register.filter
def to_unicode(mixed):
    return unicode(mixed)

Would allow a such template tag expression some_int|to_unicode|add:'foo'.

like image 194
jpic Avatar answered Oct 08 '22 21:10

jpic