ChatGPT解决这个技术问题 Extra ChatGPT

How to concatenate strings in django templates?

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.


S
Steven

Use with:

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

I was totally confused by this answer as it uses the include tag instead of the extend tag, but apparently it just works. Though I would recommend Ahsan's own answer as it also workes and is (in my opinion) semantically more correct and raises less confusion.
This may work but shouldn't be considered as a general answer to concatenate strings in django templates. See stackoverflow.com/a/23783666/781695
As the saying in Django documentation, "Strings that can be coerced to integers will be summed, not concatenated" So, for example, if you want to concatenate model object's primary keys (may be useful for create unique cache key), it does not work.
I think this doesn't escape shop_name at all, so it's dangerous.
Be aware, as already mentioned, this works with strings only! If you translate shop_name before passing it to the context in a view's get_context_data make sure it is translated using ugettext instead of ugettext_lazy.
R
Roger Dahl

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.


This should be marked as best answer because working correctly with values which can be coerced by Python as integers.
I dont know why you are not the one with the most "up" because it's your answer which is right, the "add" alone just doesn't use str() in first place and didn't work at all for me whereas your solution works flawlessly
Because the highly voted answer is the easiest - and, depending on the data, correct. If you have way for numbers to be in the field, then there is no problem. That said - having this here is a very important reminder that the data going into this tag must be considered. I +1'd both answers.
Your answer has saved me!
Remember to load your custom filter at the top of your template file: {% load <appname>_extras %}
A
Ahsan

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.


The other answers don't allow to use concatenation with extends as `extends must be the first template tag in the template
D
Daniel Holmes

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."


D
David Jay Brady

You do not need to write a custom tag. Just evaluate the vars next to each other.

"{{ shop name }}{{ other_path_var}}"

Often the simplest answers are the best ones.
This is the simplest and best answer here!
c
cezar

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.


this is not going to work. i want to add my variable in middle of path.
add filter only summed not concatenate according to django docs
The docs say "strings that can be coerced to integers will be summed". Other strings are concatenated. But that doesn't really matter anyway because you can't use the filter :(
A
Ali Sajjad

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


U
User97693321

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.


B
Bono

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.


K
K3TH3R

@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/


G
Gassan

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 }}

d
damir

You can't do variable manipulation in django templates. You have two options, either write your own template tag or do this in view,


my requirement is to do it in only templates so views option is not helpful. i also tried via custom template tag but {% load concat %} should after the {% extend .... %} tag. so how i can do it now?
Write an extended_extends tag which accepts an string format and arguments.
can u please give me an example of how to write custom tags for default ones?
I
Ignacio Vazquez-Abrams

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.


thanx for reply! for context variable i have to set in view.py which i cant due to my project requirement. and please give example of second one.
J
Jailton Silva

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