繁体   English   中英

无效的块标记“其他”。 您是否忘记注册或加载此标签?

[英]Invalid block tag 'else'. Did you forget to register or load this tag?

为什么我得到这个错误? 我在 django 上出现此错误,而它在Flask上正常工作。

1   {% if user.is_authenticated %}
2     {% extends "home.html" %}
3   {% else %}
4     {% extends "index_not_auth.html" %}
5   {% endif %}

TemplateSyntaxError at / Invalid block tag on line 3: 'else'。 您是否忘记注册或加载此标签? 请求方法:GET 请求3.2.2http://127.0.0.1:8000/ Django 版本:3.2。
第 3 行的块标记无效:“else”。 您是否忘记注册或加载此标签? 异常位置:D:\GitHub Repositories\Django-WebApp\venv\lib\site-packages\django\template\base.py,第 534 行,invalid_block_tag Python 可执行文件:D:\GitHub Repositories\Django-WebApp\venv\Scripts \python.exe Python 版本: 3.6.1

您不能将extends模板标签放在 if-else 中,模板中只能有一个extends标签,并且它必须位于模板的开头。 如果你想动态扩展模板,你应该在视图的上下文中传递模板名称,并在extends标签中使用该变量:

from django.shortcuts import render


def some_view(request):
    # ...
    context = {}
    if request.user.is_authenticated:
        context['parent_template'] = 'home.html'
    else:
        context['parent_template'] = 'index_not_auth.html'
    return render(request, 'some_template.html', context)

现在在模板中:

{% extends parent_template %}
<!-- Rest of template -->

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM