James
James

Reputation: 605

Django boilerplate template code

I am a django newbie and in creating my first project I have come to realize that a lot of my boilerplate code (the lists on the side of my page). I have to recreate them in every view and I am trying to stick with DRY but I find myself rewriting the code every time. Is there a way to inherit from my base views and just modify a few objects?

Thanks, James

Upvotes: 2

Views: 1121

Answers (5)

dzida
dzida

Reputation: 8981

If you don't decide to use context processor for some reasons (this solution looks reasonable here) you can always encapsulate some common logic into util functions and use them in your views.

You can also take a look at Generic views - this is a good way to 'stay DRY' with your code

Upvotes: 0

joel3000
joel3000

Reputation: 1319

For large blocks of static html that reappear consistently you can use the include template tag:

{% include 'static/some_file.html' %}

The includes are stored in your template file system, just like templates.

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599630

For the lists of recent articles etc, custom template tags are the thing you need. Whereas a context processor will populate your context with the lists automatically, a template tag can actually do that plus create the whole HTML markup for the column itself.

Upvotes: 3

mipadi
mipadi

Reputation: 410742

You might want to use a context processor for this work.

Upvotes: 3

Will McCutchen
Will McCutchen

Reputation: 13117

Yes, you'll want to look into template inheritance, which lets you share common elements between templates, and the {% include %} template tag, which lets you create reusable template "snippets" that can be included in other templates.

Edit: Re-reading the question, it sounds like you're talking about boilerplate code that you have in your view functions/methods that you're using to generate context shared by multiple templates. In that case, mipadi's answer is the right one: Look into context processors.

Upvotes: 3

Related Questions