首页 > 解决方案 > Django - 如何动态选择基本模板

问题描述

我想从三个可能的选项中选择要在我的 Django 项目中使用的基本模板。我从网上采购,从这个链接,我看到:

使用变量。

{% extends base_template %}

并在您的视图中,将其设置为您的视图中的“base.html”,或者一个新的“ajax.html”文件,它只提供块而没有别的。

但对该答案的评论如下:

这打破了 django-compressor 离线压缩。

  1. 我不知道那个是什么意思

另一个回答说:

{% extends request.is_ajax|yesno:"app/base_ajax.html,app/base.html" %}

但我没有提出AJAX要求。从这个答案中,我发现了yesnoDjango 提供的。这仅适用于Trueor False; 更像是if-else声明。我怎样才能实现和if报表?因为这似乎是我可以实现我想要实现的目标的一种方式。但如果你有更好的选择,请把它倒出来。elseelse-if

这是我尝试过的

{% if user_type == 1 %}
{% extends 'hod_template/base.html' %}
{% load static %}
{% elif user_type == 2 %}
{% extends 'staff_template/base.html' %}
{% load static %}
{% else %}
{% extends 'student_template/base.html' %}
{% load static %}
{% endif %}

但我得到了Invalid block tag on line 4: 'elif'. Did you forget to register or load this tag?错误。

标签: djangodjango-templates

解决方案


推荐阅读