Shehzad009
Shehzad009

Reputation: 1607

Django: How to import variables in html templates

I have a django application and what I want to do is change wherever it says "Company id" in my templates. The thing it can be very tedious because I have to make this change in every template which says "Company id". So then I thought I might create another file that can store this entry, which the I can easy custom the company id.

config.py

company_no = "Company id"

This can work in my forms.py file. I can import company_no by saying

forms.py

from mmc.config import company_no

But then how can I do the same thing for templates? Importing company_no in a template - is there a way round?

Upvotes: 2

Views: 3398

Answers (3)

Daniel Roseman
Daniel Roseman

Reputation: 599906

This is what context processors are for. Define your company name in settings.py, then write a context processor that imports it from there and returns it in a dictionary - it will then be available in every template (as long as you use RequestContext to render the template).

Upvotes: 4

cEz
cEz

Reputation: 5062

You could create a shared template and use include to load it in to the main template. Then in the shared template you could load and call a custom template tag that produces a context variable and render it as usual.

Alternatively, you could create a custom context processor that loads the data automatically in to the context instance and then render it as usual in the shared template.

Upvotes: 0

marr75
marr75

Reputation: 5725

As Blender stated, you need to pass variables like this in as part of the context when you render the template. You might make a dictionary or a namedtuple that has common items stored in configuration loaded in a function.

You should also consider using template inheritance if many templates will be display the same data, then you can have methods that load the pieces of context that go with certain base templates.

Upvotes: 1

Related Questions