439👍
Use with:
{% with "shop/"|add:shop_name|add:"/base.html" as template %}
{% include template %}
{% endwith %}
158👍
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 @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.
- [Django]-What are the limitations of Django's ORM?
- [Django]-How to get GET request values in Django?
- [Django]-How do I do a not equal in Django queryset filtering?
26👍
You do not need to write a custom tag. Just evaluate the vars next to each other.
"{{ shop name }}{{ other_path_var}}"
- [Django]-Access web server on VirtualBox/Vagrant machine from host browser?
- [Django]-Can I access constants in settings.py from templates in Django?
- [Django]-How to access Enum types in Django templates
19👍
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.
- [Django]-How can I chain Django's "in" and "iexact" queryset field lookups?
- [Django]-Django – How to set default value for DecimalField in django 1.3?
- [Django]-Django REST Framework: how to substitute null with empty string?
13👍
Refer to Concatenating Strings in Django Templates:
-
For earlier versions of Django:
{{ "Mary had a little"|stringformat:"s lamb." }}
“Mary had a little lamb.”
-
Else:
{{ "Mary had a little"|add:" lamb." }}
“Mary had a little lamb.”
- [Django]-How to test auto_now_add in django
- [Django]-Django development server reload takes too long
- [Django]-Images from ImageField in Django don't load in template
4👍
And multiple concatenation:
from django import template
register = template.Library()
@register.simple_tag
def concat_all(*args):
"""concatenate all args"""
return ''.join(map(str, args))
And in Template:
{% concat_all 'x' 'y' another_var as string_result %}
concatenated string: {{ string_result }}
- [Django]-Cron and virtualenv
- [Django]-Exclude fields in Django admin for users other than superuser
- [Django]-">", "<", ">=" and "<=" don't work with "filter()" in Django
2👍
Have a look at the add
filter.
Edit: You can chain filters, so you could do "shop/"|add:shop_name|add:"/base.html"
. But that won’t work because it is up to the template tag to evaluate filters in arguments, and extends doesn’t.
I guess you can’t do this within templates.
- [Django]-How to put comments in Django templates?
- [Django]-Django middleware difference between process_request and process_view
- [Django]-What is actually assertEquals in Python?
2👍
From the docs:
This tag can be used in two ways:
{% extends "base.html" %}
(with quotes) uses the literal value “base.html” as the name of the parent template to extend.{% extends variable %}
uses the value of variable. If the variable evaluates to a string, Django will use that string as the name of the parent template. If the variable evaluates to a Template object, Django will use that object as the parent template.
So seems like you can’t use a filter to manipulate the argument. In the calling view you have to either instantiate the ancestor template or create an string variable with the correct path and pass it with the context.
- [Django]-Django storages: Import Error – no module named storages
- [Django]-Change a field in a Django REST Framework ModelSerializer based on the request type?
- [Django]-NumPy array is not JSON serializable
2👍
I found working with the {% with %}
tag to be quite a hassle. Instead I created the following template tag, which should work on strings and integers.
from django import template
register = template.Library()
@register.filter
def concat_string(value_1, value_2):
return str(value_1) + str(value_2)
Then load the template tag in your template at the top using the following:
{% load concat_string %}
You can then use it the following way:
<a href="{{ SOME_DETAIL_URL|concat_string:object.pk }}" target="_blank">123</a>
I personally found this to be a lot cleaner to work with.
- [Django]-Django: Grab a set of objects from ID list (and sort by timestamp)
- [Django]-A field with precision 10, scale 2 must round to an absolute value less than 10^8
- [Django]-How to use MySQLdb with Python and Django in OSX 10.6?
1👍
You can’t do variable manipulation in django templates.
You have two options, either write your own template tag or do this in view,
- [Django]-Django-tables2: How to use accessor to bring in foreign columns?
- [Django]-Add rich text format functionality to django TextField
- [Django]-How to serve media files on Django production environment?
1👍
@error’s answer is fundamentally right, you should be using a template tag for this. However, I prefer a slightly more generic template tag that I can use to perform any kind of operations similar to this:
from django import template
register = template.Library()
@register.tag(name='captureas')
def do_captureas(parser, token):
"""
Capture content for re-use throughout a template.
particularly handy for use within social meta fields
that are virtually identical.
"""
try:
tag_name, args = token.contents.split(None, 1)
except ValueError:
raise template.TemplateSyntaxError("'captureas' node requires a variable name.")
nodelist = parser.parse(('endcaptureas',))
parser.delete_first_token()
return CaptureasNode(nodelist, args)
class CaptureasNode(template.Node):
def __init__(self, nodelist, varname):
self.nodelist = nodelist
self.varname = varname
def render(self, context):
output = self.nodelist.render(context)
context[self.varname] = output
return ''
and then you can use it like this in your template:
{% captureas template %}shop/{{ shop_name }}/base.html{% endcaptureas %}
{% include template %}
As the comment mentions, this template tag is particularly useful for information that is repeatable throughout a template but requires logic and other things that will bung up your templates, or in instances where you want to re-use data passed between templates through blocks:
{% captureas meta_title %}{% spaceless %}{% block meta_title %}
{% if self.title %}{{ self.title }}{% endif %}
{% endblock %}{% endspaceless %} - DEFAULT WEBSITE NAME
{% endcaptureas %}
and then:
<title>{{ meta_title }}</title>
<meta property="og:title" content="{{ meta_title }}" />
<meta itemprop="name" content="{{ meta_title }}">
<meta name="twitter:title" content="{{ meta_title }}">
Credit for the captureas tag is due here: https://www.djangosnippets.org/snippets/545/
- [Django]-Django template how to look up a dictionary value with a variable
- [Django]-Django auto_now and auto_now_add
- [Django]-How to add multiple objects to ManyToMany relationship at once in Django ?
1👍
How about this! We have first_name
and last_name
, which we want to display space " "
separated.
{% with first_name|add:' '|add:last_name as name %}
<h1>{{ name }}</h1>
{% endwith %}
What we’re actually doing is: first_name + ' ' + last_name
- [Django]-How to mix queryset results?
- [Django]-How to understand lazy function in Django utils functional module
- [Django]-Django 1.7 – App 'your_app_name' does not have migrations
0👍
extends
has no facility for this. Either put the entire template path in a context variable and use that, or copy the exist template tag and modify it appropriately.
- [Django]-Pulling data to the template from an external database with django
- [Django]-How to implement FirebaseDB with a Django Web Application
- [Django]-How to solve "Page not found (404)" error in Django?
0👍
In my project I did it like this:
@register.simple_tag()
def format_string(string: str, *args: str) -> str:
"""
Adds [args] values to [string]
String format [string]: "Drew %s dad's %s dead."
Function call in template: {% format_string string "Dodd's" "dog's" %}
Result: "Drew Dodd's dad's dog's dead."
"""
return string % args
Here, the string you want concatenate and the args can come from the view, for example.
In template and using your case:
{% format_string 'shop/%s/base.html' shop_name as template %}
{% include template %}
The nice part is that format_string can be reused for any type of string formatting in templates
- [Django]-How can I get tox and poetry to work together to support testing multiple versions of a Python dependency?
- [Django]-Adding django admin permissions in a migration: Permission matching query does not exist
- [Django]-Stack trace from manage.py runserver not appearing
-1👍
In my case I needed to concatenate to send a string concatenated by parameter to a simple_tag and I didn’t need the with, which saves 2 lines:
{% method firstParam "stringSecondParam="|add:valueSecondParam thirdParam as result %}
In this case the solution to the problem would be: "string="|add:object
- [Django]-Django admin default filter
- [Django]-What is the use of PYTHONUNBUFFERED in docker file?
- [Django]-Django-Bower + Foundation 5 + SASS, How to configure?