tags:

views:

76

answers:

5

Hi,

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

+3  A: 

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.

Will McCutchen
+3  A: 

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

mipadi
+3  A: 

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.

Daniel Roseman
A: 

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

Lukasz Dziedzia
+1  A: 

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.

joel3000