Skip to main content
 首页 » 编程设计

python之Django之包含模板继承

2025年05月04日32sharpest

我有一个网络应用程序,用户可以在其中拥有个人资料(有点像 facebook),他们可以查看自己的个人资料以及其他人的个人资料。您在自己的个人资料中看到的就是所有内容,但查看您的个人资料的其他人可能无法看到其中的所有内容。

为了实现这一点,我有 common-profile.html 和 profile.html,其中 profile.html 包括 common-profile.html 并且 common-profile.html 是每个人都可以看到的。因此,如果我想查看自己的个人资料,我会看到 profile.html,但其他人会看到 common-profile.html。

问题是,当我使用模板继承时,这两个模板都继承自某个基本模板,因此模板被导入了两次。

配置文件.html:

{% extends 'base.html' %} 
 
{% block content %} 
{% include 'common-profile.html' %} 
...other stuff would go here 
{% endblock %} 

通用配置文件.html:

{% extends 'base.html' %} 
 
{% block content %} 
<h1>{{c_user.first_name}} {{c_user.last_name}}<h1> 
...other stuff would go here 
{% endblock %} 

这只是个坏主意吗?我应该只有一个配置文件并检查权限/在模板标签中使用一些 if 语句吗?我不想在我的 html 页面中有太多逻辑,但如果它只是一些 if 语句来决定显示什么,也许没问题?

请您参考如下方法:

如果不使用包含,而是让 profile.html 扩展 common-profile.html 怎么样?然后在通用配置文件模板中有一个空 block ,非通用配置文件模板可以向其中添加内容。像这样:

通用配置文件.html:

{% extends 'base.html' %} 
 
{% block content %} 
    <!-- Normal common profile stuff --> 
 
    {% block extendedcontent %}{% endblock extendedcontent %} 
{% endblock content %} 

个人资料.html:

{% extends 'common-profile.html' %} 
 
{% block extendedcontent %} 
    <!-- Special profile stuff --> 
{% endblock extendedcontent %}