有条件地在Django中扩展模板

时间:2015-01-02 20:41:14

标签: python django django-templates

我在Django网站上有一个下载页面,我希望为登录用户和非登录用户提供服务。而不是拥有user_download.html和login_download.html,我希望有一个download.html有条件地扩展正确的基础。

但是,当我使用以下代码时出现错误。

{% if user.is_authenticated %}
  {% extends 'user_base.html' %}
{% else %}
  {% extends 'login_base.html' %}
{% endif %}

{% block content %}
<h2>Downloadable content</h2> 
...
{% endblock %}

我收到的错误是 在/ download /

的TemplateSyntaxError

无效的块标记:'else'

别的怎么了?我试过了

{% if user.is_authenticated %}
  {% extends 'user_base.html' %}
{% else %}{% if AnonymousUser.is_authenticated %}
  {% extends 'login_base.html' %}
{% endif %}{% endif %}

{% block content %}
<h2>Downloadable content</h2> 
...
{% endblock %}

但这也行不通。

谢谢, erip

2 个答案:

答案 0 :(得分:4)

{% extends %}标记支持变量。请参阅the doc以供参考。

def my_view(request):
   if request.user.is_authenicated
       base_template_name = 'user_base.html'
   else:
       base_template_name = 'login_base.html'

   # Pass base template name to the renderer
   return render_to_response('your_template.html', {'base_template_name':base_template_name})

模板(请注意,该值未引用):

{% extends base_template_name %}
...

答案 1 :(得分:1)

您收到错误,因为需要在模板顶部定义extendsextends控制模板继承:你基本上是从某个父类创建一个子类,这就是为什么extends需要成为模板中的第一件事。

想象一下写一个班级,并在__init__()中说出类似

的内容
class DoesntKnowWhereToInheritFrom(object):

    def __init__():
        if something:
            self.inherits_from(x)
        else
            self.inherits_from(y)

编译器/解释器会吓坏

在此处执行操作的常用方法是检查is_authenticated中的view,然后呈现相应的模板。

相关问题