HudsonBarroso
HudsonBarroso

Reputation: 535

How to slice in django template by a string

I just want to slice a string on django in two parts, passing a caracter like "|"

Example: 2007-007134|10003L

Part 1: 2007-007134

Part 2: 10003L

I tried somethings but without success

Someone can help me?

Upvotes: 0

Views: 1291

Answers (2)

HudsonBarroso
HudsonBarroso

Reputation: 535

I solved according Maciej Rogosz recommended: Custom Template Tag

First: I created the folder templatetags inside of my app, after that create a empty ini.py and finally created my custom_tag.py:

from django import template
register = template.Library()

@register.filter(name='split1')
def split1(value, key):
  return value.split(key)[1]

@register.filter(name='split2')
def split2(value, key):
  return value.split(key)[0]

In my tamplate I have to load the template tags

{% load custom_tags %} 

And call my custom_tags: split1, split2

{{ instance.mat_code|split1:"|" }}
{{ instance.mat_code|split2:"|" }}

That is it, python + django = Magic

Tks to everyone for your help

Ref1: https://www.w3schools.com/python/ref_string_split.asp

Ref2: https://www.codementor.io/@hiteshgarg14/creating-custom-template-tags-in-django-application-58wvmqm5f

Upvotes: 0

Maciej Rogosz
Maciej Rogosz

Reputation: 92

Create a custom template tag. They are basically python code which you can execute from inside the html templates (when using defult Django templating engine).

You can read more about them here:

https://docs.djangoproject.com/en/3.1/howto/custom-template-tags/ https://www.codementor.io/@hiteshgarg14/creating-custom-template-tags-in-django-application-58wvmqm5f

Upvotes: 1

Related Questions