gpt4 book ai didi

python - 无效的 block 标记 'else'。您是否忘记注册或加载此标签?

转载 作者:行者123 更新时间:2023-12-02 16:13:11 25 4
gpt4 key购买 nike

为什么会出现这个错误?我在 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'. Did you forget to register or load this tag?Request Method: GETRequest URL: http://127.0.0.1:8000/Django Version: 3.2.2Exception Type: TemplateSyntaxErrorException Value:
Invalid block tag on line 3: 'else'. Did you forget to register or load this tag?Exception Location: D:\GitHub Repositories\Django-WebApp\venv\lib\site-packages\django\template\base.py, line 534, in invalid_block_tagPython Executable: D:\GitHub Repositories\Django-WebApp\venv\Scripts\python.exePython Version: 3.6.1

最佳答案

不能将 extends 模板标签放在 if-else 中,一个模板中只能有一个 extends 标签,而且它必须在模板的开头.如果您想动态扩展模板,您应该在 View 的上下文中传递模板名称,并在 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 -->

关于python - 无效的 block 标记 'else'。您是否忘记注册或加载此标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67490509/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com