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

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

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

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


当前回答

参考在Django模板中连接字符串:

对于早期版本的Django: {{"Mary有一个小"|stringformat:"s lamb。"}}

“玛丽有一只小羊羔。”

其他: {{"玛丽有一个小"|加:"羔羊。"}}

“玛丽有一只小羊羔。”

其他回答

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

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

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

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

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

使用:

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

和多重串联:

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