3

I have a latest news block on a page. It's a piece of markup in a template and some logic fetching the last n news in a view. How can I make a reusable component of it (like some CMS have) which I can include in a template like this:

{% component "latest_news" "5" %}

for building a block with 5 last news.

Seems Inclusion tags is quite good for this purpose, but I wonder may be is there some build-in component-like feature in Django?

Vasily
  • 1,858
  • 1
  • 21
  • 34

3 Answers3

4

The closest to CMS's components functionality in Django is Inclusion tags

Vasily
  • 1,858
  • 1
  • 21
  • 34
  • Is this still accurate in 2018? – Scott Skiles Jul 20 '18 at 19:17
  • Yes, so far as I know. I found this question looking for a way to organise my code so that the Include templates and the context data they need and the views called can be repacked at will. I think in Django this division only naturally happens at the app level, but a site/project is intended to be a construct with a number of 'apps'. I'm getting along with a template architecture resembling this: https://oncampus.oberlin.edu/webteam/2012/09/architecture-django-templates – Atcrank Jul 24 '18 at 05:35
  • Since Django 2.0, it is also possible to specify a renderer and a template specific to each form. I haven't played around with this, but forms occupy the right sort of space in Django to allow you to generate part of a DOM, rather than a full page. This would perhaps allow an architecture heavy on forms to make the 'views' very flexibly present components. – Atcrank Jul 26 '18 at 00:42
2

In 2021, I have come across the following projects:

I have used django-render-partial pretty extensively, and I like that the interface allows your partials to be used in templates, or hooked directly up to a urls.py.

django-components looks pretty cool, because it allows you to package CSS and JS files with the use of a Media class (similarly to Django forms), but it fractures the "everything is a view" pattern provided by django-render-partial.

kbuilds
  • 991
  • 11
  • 19
1

I used django_components which saved me a lot of pain, it supports creating reusable components with dynamic components name, and it also allows passing HTML fragments to the components.