Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String manipulation in Django templates

Imagine the context variable {{ url }} outputs www.example.com/<uuid-string> where <uuid-string> is different every time, whereas the former part of the URL stays the same.

Can one change the output of {{ url }} to instead www.forexample.com/<uuid-string>, via solely manipulating the string in the template and without involving views.py (which I know is the better way to do it, but that's not the question).

An illustrative example would be great.

like image 668
Hassan Baig Avatar asked Jan 31 '26 11:01

Hassan Baig


1 Answers

read about filters and templatetags - they are a methods that allows you to perform some actions on variables in templates.

You can also create your own tags and filters that allow you to perform action non-built into Django template language

Simple example of such filter:

    #in templatetags.py
    @register.filter(name='duplicate')
    def duplicate(value):
        return value*2

    #in your template
    <p> {{ url|duplicate }} </p>

You can find more examples here. Also there you will find tutorial how to use and create them

like image 163
m.antkowicz Avatar answered Feb 03 '26 05:02

m.antkowicz