我的页面上有最新的新闻块。它是模板中的一段标记和一些在视图中获取最后 n 新闻的逻辑。 我怎样才能制作一个可重用的组件(就像一些 CMS 那样),我可以将其包含在这样的模板中:
{% component "latest_news" "5" %}
用于构建包含 5 条最新消息的区块。
似乎包含标签非常适合这个目的,但我想知道Django中是否有一些内置的类似组件的功能?
Django 中最接近 CMS 组件功能的是 包含标签
2021年,我遇到了以下项目:
我已经非常广泛地使用了
django-render-partial
,而且我喜欢该界面允许您在模板中使用部分内容,或者直接连接到 urls.py
。
django-components
看起来很酷,因为它允许您使用 Media
类(类似于 Django 表单)打包 CSS 和 JS 文件,但它破坏了 django-render-partial
提供的“一切都是视图”模式.
我使用了django_components,这让我省去了很多麻烦,它支持使用动态组件名称创建可重用的组件,并且还允许将 HTML 片段传递给组件。
了解 django-simple-components 对我很有用。
这里是一个小例子:
# file: templates/myapp/latest_news.html
{% load simple_components %}
{% set_component "article" %}
<div class="card">
<img src="{{ image }}" />
<h3>{{ title }}</h3>
<p>{{ description }}</p>
</div>
{% end_set_component %}
<div class="news-list">
{% component "article"
image="https://..."
title="Some lines"
description="Other text..."
%}
{% component "article" image="https://..." title="Second Post" description="Second description..." %}
</div>