无效的块标记“else”。您是否忘记注册或加载此标签?
为什么我收到这个错误?我在 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 请求 URL:http : //127.0.0.1 : 8000/
Django 版本:3.2.2
异常类型:TemplateSyntaxError 异常值:
第 3 行的块标记无效:'else'。您是否忘记注册或加载此标签?异常位置:D:GitHub RepositoriesDjango-WebAppvenvlibsite-packagesdjangotemplatebase.py,第 534 行,in invalid_block_tag Python 可执行文件:D:GitHub RepositoriesDjango-WebAppvenvScripts 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 -->