Unable to customize Django template tag

I am trying to add trailing 's' to a string if the last character of the string is not 's'. How to do this in a Django template? Below [-1] causes an error:

{{ name }}{% if name[-1] != "s" %}s{% endif %} 
+4
source share
5 answers
 {% if name|slice:"-1:"|first != "s" %}s{% endif %} 

The Django langong filter does not process fragments without a tree structure correctly, so the slice: “1” solution does not work. Also, using the first filter seems to do the trick.

+2
source

try slice filter

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

The Django template system provides tags that function similarly to some programming constructs - an if tag for boolean tests, a for tag for looping, etc. - but they are not just executed as the corresponding Python code, and the arbitrary template expressions will not be executed by the template system.

Use a slice of the built-in filter .

+1
source

Not sure if this is what you are looking for, but django has a built-in template filter that pluralizes words. He called just that: pluralize. You need something like this:

 {{name | pluralize}} 

Take a look at https://docs.djangoproject.com/en/dev/ref/templates/builtins/

+1
source

{% if name|last != "s" %} whether the work is done

0
source

Source: https://habr.com/ru/post/1391946/


All Articles