我想在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。
当前回答
Extends没有这种功能。要么将整个模板路径放在一个上下文变量中并使用它,要么复制现有模板标记并适当地修改它。
其他回答
在我的项目中,我是这样做的:
@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
例如,在这里,你想要连接的字符串和参数可以来自视图。
在模板和使用你的案例:
{% format_string 'shop/%s/base.html' shop_name as template %}
{% include template %}
好的部分是format_string可以在模板中的任何类型的字符串格式化中重用
在我的情况下,我需要concatenate发送一个参数连接到simple_tag的字符串,我不需要与,这节省了2行:
{% method firstParam "stringSecondParam="|add:valueSecondParam thirdParam as result %} 在这种情况下,问题的解决方案将是:"string="|add:object
参考在Django模板中连接字符串:
对于早期版本的Django: {{"Mary有一个小"|stringformat:"s lamb。"}}
“玛丽有一只小羊羔。”
其他: {{"玛丽有一个小"|加:"羔羊。"}}
“玛丽有一只小羊羔。”
我已经更改了文件夹层次结构
/shop_name/shop/base.html
下面也可以。
{% extends shop_name|add:"/shop/base.html"%}
现在它能够扩展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 }}