0

I have been trying to write my 1st django custom template tag, by reading the django docs.

The custom template tag I have written contains a conditional if elseif else condition.

The result is always returning the else condition.

Here is my custom template tag code:

@register.filter(name='replace_date_separator')
def replace_date_separator(value, arg):

if arg is 'fr-CA':
    return value.replace("/", '-')
elif arg is 'de' or arg is 'pl' or arg is 'ru':
    return value.replace("/", '.')
else:
    return value.replace("/", '*')

Here is my template tag:

{{ voluntary_detail.voluntary_finish_date|date:'m/Y'|replace_date_separator:voluntary_detail.language_version.language_code }}

The voluntary_detail.language_version.language_code above is the two letter language code - ru, de, en, pl, etc.

user3354539
  • 1,245
  • 5
  • 21
  • 40
  • This question is in the top five results for "django custom if else tag", also it is a question about filters. Changing the title to "django custom filter - if else condition" would help to avoid confusion. – tobltobs May 06 '16 at 20:28

1 Answers1

4

You are using the is keyword, which checks for object identity match, and hence, always fails.

Instead use == to check for equality, and do:

@register.filter(name='replace_date_separator')
def replace_date_separator(value, arg):

    if arg == 'fr-CA':
        return value.replace("/", '-')
    elif arg == 'de' or arg == 'pl' or arg == 'ru':
        return value.replace("/", '.')
    else:
        return value.replace("/", '*')

As an aside, you can simplify the elif statement to elif arg in ('de', 'pl', 'ru'):

Community
  • 1
  • 1
Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186
  • mu 無, Thanks. I actually did have the == and it would not work, but tried is and left that in when I copied the code to the thread. Thanks also for the simplified code too. – user3354539 Nov 11 '14 at 04:30