0

I have three templates:

  1. Base_template
  2. first_template
  3. second_template

first_template and second_template extend base_template. So, they have the same aside bar. And I need to pass the same context to these templates. Of course, I can make it once in the first view and then in the second. But, to my mind, it will not a good practice. Or, I can make a function in utils.py and add it to context_processors, but then It will be passed to all website.

What should I do? Give me an advice, please.

Thanks.

Q-bart
  • 1,503
  • 4
  • 22
  • 41

1 Answers1

2

You have a few options:

  1. You can use sessions - add the context to the session and then render it directly from the session in the template.

  2. Create a custom context processor; and simply ignore the variables in the other templates.

  3. Create a base view class, and then inherit from it in your other views. This way, your context is only defined once.

  4. Create a custom decorator that injects the context into the response, then decorate the methods (or classes) where you need it.

Of these four, 2 and 3 are the better ones; 4 will also work but requires that you understand how decorators work. The sessions I just added in there in case this was a temporary requirement - otherwise you should really ignore sessions and look at the others.

Community
  • 1
  • 1
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
  • Thanks! Can you help me secondly? I have chosen the third variant. Where can read about it mostly? – Q-bart Dec 23 '15 at 05:42
  • 1
    @Q-bart Start with the [official documentation](https://docs.djangoproject.com/en/1.9/topics/class-based-views/). – Burhan Khalid Dec 23 '15 at 05:44