在 Django 模板中渲染外部定义的块 [英] Render Externally Defined Block In Django Template

查看:27
本文介绍了在 Django 模板中渲染外部定义的块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为 Django 编写一个简单的类似博客的应用程序,并试图获得一个首页,帖子限制为 5,具有一次列出 100 个帖子的综合档案.(100 不现实,随便扔个数字)

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)

由于减去显示的数字后,两个页面之间的博客帖子块看起来完全相同,因此我想将相应的 HTML 放在一个单独的模板中,我可以将其包含或链接到正在呈现的实际模板.我查看了文档,include 标签看起来很有希望,但它显然呈现在当前上下文之外,这对我的事业没有帮助,因为它不会让对象循环通过.除此之外,我看不到任何其他方式来做我想做的事.这是可能的还是我只是运气不好而不得不违反 DRY?下面是代码,让您了解我想要什么.

Since the blog post blocks will look exactly the same between the two pages minus the number being shown, I'd like 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.

谢谢

#######################
# 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 %}

推荐答案

您正在寻找一个 包含标签.

这篇关于在 Django 模板中渲染外部定义的块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆