| 332 | | Subclassing Context: Custom subclasses |
|---|
| 333 | | -------------------------------------- |
|---|
| 334 | | |
|---|
| 335 | | Feel free to subclass ``Context`` yourself if you find yourself wanting to give |
|---|
| 336 | | each template something "automatically." For instance, if you want to give |
|---|
| 337 | | every template automatic access to the current time, use something like this:: |
|---|
| 338 | | |
|---|
| 339 | | from django.core.template import Context |
|---|
| 340 | | import datetime |
|---|
| 341 | | class TimeContext(Context): |
|---|
| 342 | | def __init__(self, *args, **kwargs): |
|---|
| 343 | | Context.__init__(self, *args, **kwargs) |
|---|
| 344 | | self['current_time'] = datetime.datetime.now() |
|---|
| 345 | | |
|---|
| 346 | | This technique has two caveats: |
|---|
| 347 | | |
|---|
| 348 | | * You'll have to remember to use ``TimeContext`` instead of ``Context`` in |
|---|
| 349 | | your template-loading code. |
|---|
| 350 | | |
|---|
| 351 | | * You'll have to be careful not to set the variable ``current_time`` when |
|---|
| 352 | | you populate this context. If you do, you'll override the other one. |
|---|
| 353 | | |
|---|