Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put variable from database into base.html template?

I'm working on a web page. There will be contact in the footer like email or telephone. This footer should be everywhere so it is in the base.html which is being extended by each template/html.

I've created a table called ContactAdmin, to provide simple and straightforward interface for admin to change his contact info. And here is the problem.

The base.html has no view (it is just for extending) so I don't know how to put there variable - email, telephone from table ContactAdmin. I thought about putting it into every view which is a huge overkill in my opinion.

So how to make Django to read this variables from database and put them into base.html?

The ContactAdmin table should have just one row

like image 638
Milano Avatar asked Mar 01 '26 14:03

Milano


1 Answers

You dont need to edit all views. Exactly for this scenario, django has template context processors. The advantage here is, since the base template is still part of the templating language, and it has access to the Context, you just need to set these variables in your custom context processor, and everything should work as is.

Some examples on how to write your custom context processors:

  • StackOverflow Example
  • Django example
like image 188
karthikr Avatar answered Mar 03 '26 03:03

karthikr