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 %}
common-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 个回答
6
你可以试试不使用包含(include),而是让 profile.html
继承 common-profile.html
。这样的话,在公共的个人资料模板里留一个空的区域,让非公共的个人资料模板可以往里添加内容。大概是这样的:
common-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 %}