我想在Django模板标签中连接一个字符串,比如:
{% extend shop/shop_name/base.html %}
这里shop_name是我的变量,我想将它与rest of path连接起来。
假设我有shop_name=example.com,我想要结果扩展shop/example.com/base.html。
我想在Django模板标签中连接一个字符串,比如:
{% extend shop/shop_name/base.html %}
这里shop_name是我的变量,我想将它与rest of path连接起来。
假设我有shop_name=example.com,我想要结果扩展shop/example.com/base.html。
当前回答
和多重串联:
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 }}
其他回答
我已经更改了文件夹层次结构
/shop_name/shop/base.html
下面也可以。
{% extends shop_name|add:"/shop/base.html"%}
现在它能够扩展base.html页面。
看看添加过滤器。
编辑:你可以链式过滤器,所以你可以做"shop/"|add:shop_name|add:"/base.html"。但这是行不通的,因为它由模板标记来计算参数中的过滤器,而extends则不行。
我想在模板中不能这样做。
使用:
{% with "shop/"|add:shop_name|add:"/base.html" as template %}
{% include template %}
{% endwith %}
Extends没有这种功能。要么将整个模板路径放在一个上下文变量中并使用它,要么复制现有模板标记并适当地修改它。
我发现使用{% with %}标记非常麻烦。相反,我创建了下面的模板标记,它应该适用于字符串和整数。
from django import template
register = template.Library()
@register.filter
def concat_string(value_1, value_2):
return str(value_1) + str(value_2)
然后在模板的顶部使用以下方法加载模板标签:
{% load concat_string %}
你可以这样使用它:
<a href="{{ SOME_DETAIL_URL|concat_string:object.pk }}" target="_blank">123</a>
我个人觉得这样工作起来更简洁。