我想在Django模板标签中连接一个字符串,比如:

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

这里shop_name是我的变量,我想将它与rest of path连接起来。

假设我有shop_name=example.com,我想要结果扩展shop/example.com/base.html。


当前回答

你不能在django模板中做变量操作。 你有两个选择,要么写你自己的模板标签,要么在视图中这样做,

其他回答

您不需要编写自定义标记。只需要对相邻的变量求值。

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

不要对字符串使用add,你应该这样定义一个自定义标签:

创建一个文件:<appname>\templatetags\<appname>_extra .py

from django import template

register = template.Library()

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

然后像@Steven说的那样使用它

{% load <appname>_extras %}

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

避免添加的原因:

根据文件

这个过滤器将首先尝试将两个值强制转换为整数… 可以强制转换为整数的字符串将被求和,而不是连接…

如果两个变量都是整数,结果就会出乎意料。

在我的情况下,我需要concatenate发送一个参数连接到simple_tag的字符串,我不需要与,这节省了2行:

{% method firstParam "stringSecondParam="|add:valueSecondParam thirdParam as result %} 在这种情况下,问题的解决方案将是:"string="|add:object

从文档中可以看出:

这个标签可以用两种方式使用:

{% extends "base.html" %}(带引号)使用字面值"base.html"作为要扩展的父模板的名称。 {% extends variable %}使用variable的值。如果变量的值是一个字符串,Django将使用该字符串作为父模板的名称。如果变量的值是一个Template对象,Django将使用该对象作为父模板。

看起来你不能用过滤器来操纵这个论证。在调用视图中,您必须实例化祖先模板,或者使用正确的路径创建一个字符串变量,并将其与上下文一起传递。

和多重串联:

from django import template
register = template.Library()


@register.simple_tag
def concat_all(*args):
    """concatenate all args"""
    return ''.join(map(str, args))

在Template中:

{% concat_all 'x' 'y' another_var as string_result %}
concatenated string: {{ string_result }}