ram1
ram1

Reputation: 6470

Can't substring in Django template tag

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

Answers (5)

Udi
Udi

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

mattre
mattre

Reputation: 1

{% if name|last != "s" %} does the job

Upvotes: 0

Timmy O'Mahony
Timmy O'Mahony

Reputation: 53981

try the slice filter

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

Upvotes: 5

akhaku
akhaku

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

Paulo Scardine
Paulo Scardine

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

Related Questions