我想在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 }}
其他回答
不要对字符串使用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 %}
避免添加的原因:
根据文件
这个过滤器将首先尝试将两个值强制转换为整数… 可以强制转换为整数的字符串将被求和,而不是连接…
如果两个变量都是整数,结果就会出乎意料。
这个怎么样!我们有first_name和last_name,我们希望将它们分开显示为空格“”。
{% with first_name|add:' '|add:last_name as name %}
<h1>{{ name }}</h1>
{% endwith %}
我们实际做的是:first_name + ' ' + last_name
和多重串联:
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 }}
使用:
{% with "shop/"|add:shop_name|add:"/base.html" as template %}
{% include template %}
{% endwith %}
我已经更改了文件夹层次结构
/shop_name/shop/base.html
下面也可以。
{% extends shop_name|add:"/shop/base.html"%}
现在它能够扩展base.html页面。