I've this string 'doc.specalization.name' from my views that I'm rendering in templates to see if it ends with 's'. It it does, I want to remove the 's'

I tried this code but i get Could not parse the remainder: '('s')' from 'doc.specialization.name.endswith('s')'

 {% if doc.specialization.name.endswith('s') %}
        <h3> {{doc.specialization.name|slice:":-1"}} </h3>   
 {% endif %}

3 Answers

dylrei On

You're better off doing this in your view code than in a template. For example:

for doc in doc_records:
    if doc.specialization.name.endswith('s'):
        doc.specialization.name = doc.specialization.name[:-1]

But don't save the record, assuming this is just for display purposes

karthikr On

You cannot run python code in a django template. You can use a builtin filter for this:

{% ifequal doc.specialization.name|default:""|slice:"-1" "s" %}
    {# do your stuff #}
{% endifequal %}

The default is only a fallback for None values

Documentation on slice here

You could even use the with tag to avoid computing the same thing multiple times

sv_rancher On

Karthikr's answer is close. Ifequal is scheduled to be deprecated in future versions of Django, so you may want to use the method below. You also need to add a ':' after the '-1'.

{% if doc.specialization.name|default:""|slice:"-1:" == "s" %}
  <h3> {{ doc.specialization.name|slice:":-1" }} </h3>
{% else %}
  <h3> {{ doc.specialization.name }} </h3>
{% endif %}