The word "context" refers to data that can be used during the rendering of a page.
There are two ways to get context into each page. The first is via template comments.
Writing
{# title = More About Context #}
at the top of the HTML page will create the variable title
that
can be used in the page as {{ page.title }}
to produce: More About Contexts
To add more variables list them one on each line. To add data beyond a simple string use the JSON format:
{# title = More About Context #}
{# foo = 1234.5 #}
{# bar = [ 100, 200, 'Hello World' ] #}
Note that in the last example for bar
gets turned into python list accessible as
{{ page.bar }}
to produce [100, 200, u'Hello World'].
The {{ page.bar }}
object can also be looped over with Django
to produce:
100
200
Hello World
The second method of getting context into a page is a python module named context.py
placed in the directory root. This may contain
any python construct. Make sure that this python module can be executed without errors.
The content of this module will be visible under the parameter data
{{ context }}
variable name.
Example supposed that the context.py
file contains the following:
#
# The data file named context.py in the root folder
# will be loaded automatically into the page.
#
NUMBERS = range(5)
# It may contain any valid python construct.
def say_hello(name):
return "Hello %s" % name
greeting = say_hello("World!")
This file has to be in the root location of the site. We can now access the contents of this module
via context
variable like
so {{ context.greeting }}
will produce: Hello World!
Go back to: Home Page .