Skip to main content
 首页 » 编程设计

python之Django block.super 不呈现父模板中的变量集

2024年08月28日25bhlsheji

我有以下场景:

2 次浏览:

View 1:

return render(request, 'template1.html', {'var1': 'value1'} ) 

View 2:

return render(request, 'template2.html', {'var2': 'value2' } ) 

2个模板:

template1.html

{% block foo %} 
{{ var1 }} 
{% endblock %} 

template2.html

{% extends template1.html %} 
{% block foo %} 
{{ block.super }} 
{{ var2 }} 
{% endblock %} 

Template1.html 的期望输出:

value1 

Template1.html 的实际输出:

value1 

Template2.html 的预期输出:

value1 value2 

实际输出:

value2 

为什么调用{{block.super}}时没有输出'var1'的值?

我在 settings.py 中定义了“django.core.context_processors.request”。我错过了什么?

请您参考如下方法:

template2.html 扩展了 template1.html,但这并不意味着 view2 扩展了 view1。需要在view2的上下文信息中添加var1。

# view2 
return render(request, 'template2.html', { 
    'var1': 'value1', 
    'var2': 'value2' 
})