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 %}
try the slice filter
{% if name|slice:"-1" != "s" %}
{% 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With