Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django templates built-in filters: Using a variable value in an argument

Using Django's built-in yesno filter, I need to insert one of these values:

  1. The word "I"
  2. The value of the variable owner_name

Here's the code I've tried to use in my template:

"Look what {{ is_owner|yesno:"I,{{ owner_name }}" }} created!"

Using the code above causes the following error:

Could not parse the remainder: ':"I,{{ owner_name' from 'is_owner|yesno:"I,{{ owner_name'

So how do I escape a variable inside a filter's argument?

like image 487
burtyish Avatar asked Oct 29 '13 16:10

burtyish


2 Answers

Another thing you can do is concatenate the arguments using the with template tag and add filter:

{% with yesno_args="I,"|add:owner_name %}
"Look what {{ is_owner|yesno:yesno_args }} created!"
{% endwith %}

I think this is simpler than having to add a custom filter.

like image 90
imiric Avatar answered Oct 09 '22 15:10

imiric


You can create a custom filter to do what you want.

It would look something like {{ is_owner|my_yesno:owner_name }}

With the custom filter

from django.template.defaultfilters import yesno

def my_yesno(value, arg):
   yes_no_list = ['I', arg]
   return yesno(value, yes_no_list)

This would let you reuse yesno while creating the list in your wrapper my_yesno. You can alternatively just write your own logic if you want to do something differently as well. Be sure to {% load %} your custom filter as well.

like image 2
Tim Edgar Avatar answered Oct 09 '22 14:10

Tim Edgar