Django - 包含的模板继承

时间:2011-01-23 23:35:17

标签: python django

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

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

问题在于,当我使用模板继承时,这两个模板都从某个基本模板继承,因此模板会被导入两次。

profile.html:

{% extends 'base.html' %}

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

共profile.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语句来决定要显示什么,也许那没关系?

1 个答案:

答案 0 :(得分:6)

如果不是使用包含,那么您profile.htmlcommon-profile.html延长{% extends 'base.html' %} {% block content %} <!-- Normal common profile stuff --> {% block extendedcontent %}{% endblock extendedcontent %} {% endblock content %} ?然后在公共配置文件模板中只有一个空块,非公共配置文件模板可以添加内容。像这样:

共profile.html:

{% extends 'common-profile.html' %}

{% block extendedcontent %}
    <!-- Special profile stuff -->
{% endblock extendedcontent %}

profile.html:

{{1}}