How to concatenate strings in django templates? How to concatenate strings in django templates? django django

How to concatenate strings in django templates?


Use with:

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


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 templateregister = template.Library()@register.filterdef addstr(arg1, arg2):    """concatenate arg1 & arg2"""    return str(arg1) + str(arg2)

and then use it as @Steven says

{% load <appname>_extras %}{% with "shop/"|addstr:shop_name|addstr:"/base.html" as template %}    {% include template %}{% endwith %}

Reason for avoiding add:

According to the docs

This filter will first try to coerce both values to integers...Strings that can be coerced to integers will be summed, not concatenated...

If both variables happen to be integers, the result would be unexpected.


I have changed the folder hierarchy

/shop/shop_name/base.html To /shop_name/shop/base.html

and then below would work.

{% extends shop_name|add:"/shop/base.html"%} 

Now its able to extend the base.html page.