How to concatenate strings in django templates

0 votes

I want to concatenate a string in a Django template tag, like:

{% extend shop/shop_name/base.html %}

Here shop_name is my variable and I want to concatenate this with rest of path.

Suppose I have shop_name=example.com and I want result to extend shop/example.com/base.html.

Aug 3, 2020 in Python by kartik
• 37,520 points
11,415 views

1 answer to this question.

0 votes

Hello @kartik,

Don't use add for strings, you should define a custom tag like this :

Create a file : <appname>\templatetags\<appname>_extras.py

from django import template

register = template.Library()

@register.filter
def addstr(arg1, arg2):
    """concatenate arg1 & arg2"""
    return str(arg1) + str(arg2)

and then use it as:

{% load <appname>_extras %}

{% with "shop/"|addstr:shop_name|addstr:"/base.html" as template %}
    {% include template %}
{% endwith %}

Hope this is helpfUll!!

Thank You!!

answered Aug 3, 2020 by Niroj
• 82,880 points

Related Questions In Python

0 votes
1 answer

How to format strings in python?

To answer your first question... .format just seems more ...READ MORE

answered Oct 1, 2018 in Python by aryya
• 7,460 points
807 views
0 votes
1 answer

How to switch pages using Ajax in Django?

You should use django-pjax which is built exactly for ...READ MORE

answered Oct 9, 2018 in Python by aryya
• 7,460 points
1,552 views
0 votes
1 answer

How to get all related Django model objects in Python?

This actually gives you the property names ...READ MORE

answered Nov 14, 2018 in Python by Nymeria
• 3,560 points

edited Dec 18, 2018 by Nymeria 6,782 views
0 votes
1 answer

How to run django unit-tests on production database in Python?

In case someone googles here searching for ...READ MORE

answered Nov 28, 2018 in Python by Nymeria
• 3,560 points
1,518 views
0 votes
1 answer

How to temporarily disable a foreign key constraint in MySQL?

Hello @kartik, To turn off foreign key constraint ...READ MORE

answered Jun 23, 2020 in Python by Niroj
• 82,880 points
2,340 views
0 votes
1 answer

How do I use Django templates without the rest of Django?

Hello @kartik, Let's say you have this important ...READ MORE

answered Jun 23, 2020 in Python by Niroj
• 82,880 points
1,494 views
0 votes
1 answer

How to query as GROUP BY in django?

Hii, Django does not support free group by ...READ MORE

answered Apr 23, 2020 in Python by Niroj
• 82,880 points
6,251 views
0 votes
1 answer

How to load a custom JS file in Django admin home?

Hello @kartik, You can override templates/admin/index.html and add the JavaScript ...READ MORE

answered May 14, 2020 in Python by Niroj
• 82,880 points
7,814 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP