Pageparts extending templates
Suppose I want to repeat some easy HTML structure on my site a lot of times. For example, I want to display some parts of the pages "in green boxes".
The first mandatory step to achieve this goal would be to create a template file like this:
<!-- greenbox.html -->
<div style="background-color:#88ff88;"><br>
{% block content %}<br>
{% endblock %}<br>
</div>
Then every time I need this predefined template I have to create a separate template like the following:
<!-- pagepart_1.html -->
{% extends "greenbox.html" %}
{% block content %}
This time I want to add this dummy text in here
{% endblock %}
<!-- pagepart_2.html -->
{% extends "greenbox.html" %}
{% block content %}
The second time I want to add some other text
{% endblock %}
开发者_如何学运维
The actual page containing the green boxes will look like this:
<html><head>My Page</head>
<body>
<h1>Page Title</h1>
{% include "pagepart_1.html" %}
<br /><br />
{% include "pagepart_2.html" %}
</body></html>
This kind of approach does work, but I think it contains a little overhead. Can I avoid the creation of separate templates for each instance (pagepart_1.html, pagepart_2.html, ...)?
So can I make my main page look something like this?
<html><head>My Page</head>
<body>
<h1>Page Title</h1>
{% unkowntag extend "greenbox.html" %}
{% block content %}
This time I want to add this dummy text in here
{% endblock %}
{% endunknowntag %}
<br /><br />
{% unkowntag extend "greenbox.html" %}
{% block content %}
The second time I want to add some other text
{% endblock %}
{% endunknowntag %}
</body></html>
Thanks a lot!
That's the only approach available it you want to allow for completely customizable content areas. However, if you can standardize the content, such that it will always display an unordered list, for example, you can do:
<!-- greenbox.html -->
<div style="background-color:#88ff88;"><br>
<ul>
{% for item in list %}
<li>{{ item }}</li>
{% endfor %}
</ul>
</div>
And then in your template:
<!-- mypage.html -->
{% with something as list %}
{% include 'greenbox.html' %}
{% endwith %}
You can do much more complex structures and even pass multiple variables (in Django 1.3+):
<!-- greenbox.html -->
<div style="background-color:#88ff88;"><br>
<h2>{{ title }}</h2>
<img style="float:{{ float }};" src="{{ image }}" alt="{{ alt_text }}">
<p>{{ description }}</p>
</div>
<!-- mypage.html -->
{% with title=obj.title image=obj.image.name alt_text=obj.title float="left" description=obj.description %}
{% include 'greenbox.html' %}
{% endwith %}
I would write a custom tag that emits the HTML and use it multiple times.
精彩评论