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 %}
{% 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.
try slice filter
{% if name|slice:"-1" != "s" %}
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 .
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/
{% if name|last != "s" %} whether the work is done
{% if name|last != "s" %}
Source: https://habr.com/ru/post/1391946/More articles:How to add margin without squeezing content off the screen? - cssWhy is D3D10SDKLayers.dll loading during my DX11 game? - c ++mySQL for PHP for JSON: String cannot be converted to JSONObject - javaHow to scroll WebView to a specific point on Android - androidMySQL - increasing a column value or inserting data if not. - mysqlAutomatic Runtime Performance Regression Test in Java - javaZODB PersistentLists loading lazily? - pythonHistory of dead locks - sql-serverHow to change multiple tables at once in mysql? - mysqlDCT Fast Conversion - algorithmAll Articles