Reputation: 6470
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 %}
Upvotes: 5
Views: 4557
Reputation: 4872
{% 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.
Upvotes: 3
Reputation: 1157
Not sure if this is what you're looking for, but django has a built-in template filter that pluralizes words. It's called just that: pluralize. You'd want something like this:
{{name | pluralize}}
Take a look at https://docs.djangoproject.com/en/dev/ref/templates/builtins/
Upvotes: 1
Reputation: 77261
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.
Upvotes: 1