3👍
using templatetags
split would be something like this:
as templatetags
only takes one argument
, but for split with max limit we need to pass two arguments
.
in such case we can combind the two arguments as a string and use a separator.
here for example i’m using ||||
as two arguments separator
in your app folder create one folder, named templatetags
there create a file split.py
:
from django import template
register = template.Library()
@register.filter
def split(splitable, split_at):
# split with max limit
if len(split_at.split("||||")) == 2:
return splitable.split(split_at.split("||||")[0], int(split_at.split("||||")[1]))
# normal split without max limitation
return splitable.split(split_at)
now it’s better to restart your server once.
then in template do:
{% load split %}
<!-- first element no split limit -->
{{ str1|split:"-"|first }}
<!-- first element with split limit, in following example, the limit is 1 -->
{{ str1|split:"-||||1"|first }}
<!-- last element no split limit -->
{{ str1|split:"-"|last }}
<!-- last element with split limit, in following example, the limit is 1 -->
{{ str1|split:"-||||1"|last }}
<!-- element by index no split limit -->
{% with str1|split:"-" as split_data %}{{ split_data.0 }}{% endwith %}
<!-- element by index with split limit, in following example, the limit is 1 -->
{% with str1|split:"-||||1" as split_data %}{{ split_data.0 }}{% endwith %}
0👍
In Your Template you need to directly use the converted value because there is no way filter to split text in templates
{{ part1 }} {{ part2 }}
- [Django]-Django Forms for generic relationships. How to include them?
- [Django]-Razorpay django integration
- [Django]-Django Create Multiple Objects (Same Model) From One Form
- [Django]-Migrate user groups and permissions in Django?
- [Django]-Django celery: scheduling recurring task but with fixed start date
Source:stackexchange.com