我想在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/"|add:shop_name|add:"/base.html"。但这是行不通的,因为它由模板标记来计算参数中的过滤器,而extends则不行。

我想在模板中不能这样做。

@error的答案基本上是正确的,你应该使用一个模板标签。然而,我更喜欢一个稍微更通用的模板标签,我可以使用它来执行类似于这样的任何类型的操作:

from django import template
register = template.Library()


@register.tag(name='captureas')
def do_captureas(parser, token):
    """
    Capture content for re-use throughout a template.
    particularly handy for use within social meta fields 
    that are virtually identical. 
    """
    try:
        tag_name, args = token.contents.split(None, 1)
    except ValueError:
        raise template.TemplateSyntaxError("'captureas' node requires a variable name.")
    nodelist = parser.parse(('endcaptureas',))
    parser.delete_first_token()
    return CaptureasNode(nodelist, args)


class CaptureasNode(template.Node):
    def __init__(self, nodelist, varname):
        self.nodelist = nodelist
        self.varname = varname

    def render(self, context):
        output = self.nodelist.render(context)
        context[self.varname] = output
        return ''

然后你可以像这样在模板中使用它:

{% captureas template %}shop/{{ shop_name }}/base.html{% endcaptureas %}
{% include template %}

正如注释所提到的,这个模板标签对于在整个模板中可重复的信息特别有用,但需要逻辑和其他东西,会堵塞你的模板,或者在你想重用模板之间通过块传递的数据的情况下:

{% captureas meta_title %}{% spaceless %}{% block meta_title %}
    {% if self.title %}{{ self.title }}{% endif %}
    {% endblock %}{% endspaceless %} - DEFAULT WEBSITE NAME
{% endcaptureas %}

然后:

<title>{{ meta_title }}</title>
<meta property="og:title" content="{{ meta_title }}" />
<meta itemprop="name" content="{{ meta_title }}">
<meta name="twitter:title" content="{{ meta_title }}">

captureas标签的出处在这里:https://www.djangosnippets.org/snippets/545/

这个怎么样!我们有first_name和last_name,我们希望将它们分开显示为空格“”。

{% with first_name|add:' '|add:last_name as name %}
    <h1>{{ name }}</h1>
{% endwith %}

我们实际做的是:first_name + ' ' + last_name

使用:

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