姜戈初学者。我有一个带有徽标的基本模板,以及内容的三个子部分。在默认情况下,其中两个子节包含html,其余的分节用于每个子页面的内容。
现在,我想创建一个不同的页面,它的标志与完全相同,但具有不同的子部分/内容。例如,我可能只想要两个子部分,水平格式而不是垂直格式等等。
因此,为此,我想我需要创建一个新的模板-问题是,我违反了干主体,在新模板中有完全相同的徽标html代码作为第一个模板。
那么,在这种情况下,是否有任何设计模式来解决重复徽标代码的问题?我正在考虑将像isPage1或isPage2这样的变量传递给模板,然后在此基础上启用/禁用块--这是一种可行的方法,任何人都能提供任何替代方法吗?
非常感谢
发布于 2013-01-17 11:30:27
是的,有一种模式完全符合你的需要。它在DJANGO中叫做模板继承。
基本上,您将有一个带有标题、徽标和主要内容占位符的基本模板。类似于(摘自我放在上面的链接):
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="style.css" />
<title>{% block title %}My amazing site{% endblock %}</title>
</head>
<body>
<div id="sidebar">
{% block sidebar %}
<ul>
<li><a href="/">Home</a></li>
<li><a href="/blog/">Blog</a></li>
</ul>
{% endblock %}
</div>
<div id="content">
{% block content %}{% endblock %}
</div>
</body>
</html>然后,在您的实际网页(使用模板的网页)上,您将拥有:
{% extends "base.html" %}
{% block title %}My amazing blog{% endblock %}
{% block content %}
{% for entry in blog_entries %}
<h2>{{ entry.title }}</h2>
<p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}注意,这里的基模板称为base.html。因此,在您的网页中,通过放置{% extends "base.html" %}扩展了 base.html。然后,在该页面中,只需为特定的block添加内容。
发布于 2017-03-07 09:28:17
You can use this inheritance concept in different way.
use same block tags to whole application
filename: index.html
<html>
<head>
---style.css files here---
{% block title %}title{% endblock %}
{% block additional_css_files %}css files{% endblock %}
{% block header %}header and header menus{% endblock %}
</head>
<body>
{% block main_content %}
your body content here
{% endblock %}
{% block scripts %}Script files{% endblock %}
</body>
</html>
filename: home.html
{% extends "index.html" %}
{% block title %}title2{% endblock %}# u can overwrite the title with new title
but if you want to use parent title no need to mention block tags in home.html
or you have to use {% block title %}{{block.super}}{% endblock %}
same concept come below.
{% block additional_css_files %}css files2{% endblock %}
{% block header %}header and header menus{% endblock %}https://stackoverflow.com/questions/14378088
复制相似问题