Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't substring in Django template tag

Tags:

django

I am trying to add a trailing 's' to a string unless the string's last character is an 's'. How do I do this in a Django template? The [-1] below is causing an error:

{{ name }}{% if name[-1] != "s" %}s{% endif %}
like image 765
ram1 Avatar asked Jan 19 '12 22:01

ram1


3 Answers

try the slice filter

{% if name|slice:"-1" != "s" %}
like image 175
Timmy O'Mahony Avatar answered Nov 18 '22 08:11

Timmy O'Mahony


{% if name|slice:"-1:"|first != "s" %}s{% endif %}

Django's slice filter doesn't handle colon-less slices correctly so the slice:"-1" solution does not work. Leveraging the |first filter in addition, seems to do the trick.

like image 20
Udi Avatar answered Nov 18 '22 09:11

Udi


The Django template system provides tags which function similarly to some programming constructs – an if tag for boolean tests, a for tag for looping, etc. – but these are not simply executed as the corresponding Python code, and the template system will not execute arbitrary Python expressions.

Use the slice built-in filter.

like image 1
Paulo Scardine Avatar answered Nov 18 '22 09:11

Paulo Scardine