Is it possible to slice the string from Django template tag's variable?
Let's say some_variable contain "abcde" I want it to be sliced to be "abc"
On Django's template, I tried like this.
{{some_variable[:-2]}}
It does not work.
If it's possible to slice words from Django template tag's variable, please advise me how to do it.
CodePudding user response:
Yes, you can work with the |slice
template filter [Django-doc]:
{{ some_variable|slice:":-2" }}
This works both for lists and strings. For example:
>>> from django.template import Template, Context
>>> Template('{{ foo|slice:":-2" }}').render(Context({'foo': 'abcde'}))
'abc'
Using {{ some_variable[:-2] }}
is not possible: Django's template language does not allow function calls, subscripting, operators, etc. Only a sublanguage of Python is supported, mainly to prevent people from writing business logic in the templates.