开发者

Render Externally Defined Block In Django Template

I'm writing a simple blog-like application for Django and am trying to get the effect of having a front page with posts limited to 5, with a comprehensive archive that lists something like 100 posts at a time. (100 is not realistic, just throwing a number out there)

Since the blog post blocks will look exactly the same between the two pages minus the number being shown, I'd l开发者_Go百科ike to put the corresponding HTML in a separate template that I can include or link to from the actual templates being rendered. I've looked over the documentation, and the include tag looked promising, but it apparently renders outside of the current context, which is not helpful to my cause, since it wouldn't get the objects to loop through. Outside of that, I can't see any other way to do what I want. Is this possible or am I just out of luck and going to have to violate DRY? Code is below to give you an idea of what I want.

Thanks

#######################
# news/frontpage.html #
#######################
{% extends "news/base.html" %}

{% block site_title %} - Front Page{% endblock %}

{% block center_col %}
{{ block.super }}
     <a href="/news/">View Older Blog Posts</a>
{% endblock %}

{% block blog_rows %}
{% for object in object_list %}
     # Blog post content would go here, however it is to be included.
{% endfor %}
{% endblock %}


You're looking for an inclusion tag.


Why don't you filter for the blog posts you want to show in your view? That way you can keep the template the same:

{% for object in blogposts %}
# ...
{% endfor %}

You define blogposts in your view, which either includes 5 or 100 posts.


Ignacio is right that you want an inclusion tag, but you should know that the include tag does not render outside the current context - it very definitely uses the same context as the block it's in.

Your problem is probably that you're trying to call blogpost_set on the object_list - but the relationship is not with the list of objects, it's with each individual object in the list. You'd need to iterate through object_list and then through blogpost_set.all on each one.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜