Django模板扩展

时间:2016-02-03 06:23:07

标签: django django-templates

我是Django的新手,并试图了解如何使用模板,我有模板扩展的问题。我有3个模板。 base.html

中的第一个
{% load staticfiles%}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
<link rel="stylesheet" type="text/css" href="{%static 'css/main.css'%}">

    <title>Home</title>
</head>
<body >
<div class="page-header">
    <h1><a href="/">Django Project</a></h1>
</div>

<div class="content container">

    <div class="row">
        <div class="col-sm-8">
            {%block content %}

            {%endblock%}
        </div>

        <div class="col-sm-4">

            {%block lastposts %}

            {%endblock%}
        </div>
    </div>
</div>
</body>
</html>

第二个是 post_list.html (我从视图中呈现)

{% extends 'blog/base.html' %}

{% block content %}

{%for post in posts %}
    <a href=""><h1>{{post.title}}</h1></a>
    <p>{{post.text|linebreaks}}</p>
    <p><b>Author: </b>{{post.author}}</p>
    <p><b>Published Date: </b>{{post.published_date}}</p>
{%endfor%}

{% endblock %}

latest_posts.html

{% extends 'blog/base.html' %}
{% block lastposts %}
<h3>Latest Posts</h3>

{%for post in posts%}
<a href=""><h4>{{post.title}}</h4></a>
{% endfor %}
{% endblock %}

问题是latest_posts.html的内容没有显示出来。我知道有些事情是错的。在这种情况下,我如何使用django中的扩展来分离这3个文件中的代码。感谢。

* UPDATE

views.py

from django.shortcuts import render
from django.utils import timezone

from .models import Post


# Create your views here.
def post_list(request):
    posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
    return render(request, 'blog/post_list.html', {'posts': posts})

urls.py

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.post_list, name='post_list'),
]

1 个答案:

答案 0 :(得分:0)

如果您想在post_list.html中显示latest_posts.html的内容,则必须将其包含在内

<强> post_list.html

DateTime

latest_posts.html (仅移除{% extends 'blog/base.html' %} {% block content %} {%for post in posts %} <a href=""><h1>{{post.title}}</h1></a> <p>{{post.text|linebreaks}}</p> <p><b>Author: </b>{{post.author}}</p> <p><b>Published Date: </b>{{post.published_date}}</p> {%endfor%} {% endblock %} {%block lastposts %} {% include 'blog/latest_posts.html' %} {% endblock %} extend代码)

block