2

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

asked Jul 14, 2010 at 20:56

5 Answers 5

3

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.

answered Jul 14, 2010 at 21:10
Sign up to request clarification or add additional context in comments.

Comments

3

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

answered Jul 14, 2010 at 21:10

Comments

3

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.

answered Jul 14, 2010 at 21:39

Comments

1

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.

answered Jul 16, 2010 at 17:03

Comments

0

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

answered Jul 14, 2010 at 22:04

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.