1 of 18

Templates

B. Krishnakumar

2 of 18

  • we returned the text in our example views.
  • Namely, the HTML was hard-coded directly in our Python code, like this:
  • def current_datetime(request):
  • now = datetime.datetime.now()
  • html = "<html><body>It is now %s.</body></html>" % now
  • return HttpResponse(html)

3 of 18

  • not a good idea to hardcode HTML directly in your views. Here’s why:
  • Any change to the design of the page requires a change to the Python code. The design of a site tends to change far more frequently than the underlying Python code, so it would be convenient if the design could change without needing to modify the Python code.
  • • Writing Python code and designing HTML are two different disciplines, and most professional Web development environments split these responsibilities between separate people (or even separate departments). Designers and HTML/CSS coders shouldn’t be required to edit Python code to get their job done.
  • • It’s most efficient if programmers can work on Python code and designers can work on templates at the same time, rather than one person waiting for the other to finish editing a single file that contains both Python and HTML.
  • For these reasons, it’s much cleaner and more maintainable to separate the design of the page from the Python code itself. We can do this with Django’s template system

4 of 18

  • Template
  • A Django template is a string of text that is intended to separate the presentation of a document from its data.
  • A template defines placeholders and various bits of basic logic (template tags) that regulate how the document should be displayed.
  • Usually, templates are used for producing HTML, but Django templates are equally capable of generating any text-based format.

5 of 18

  • This Django template describes an HTML page that thanks a person for placing an order with a company (refer)

6 of 18

  • not yet going to integrate it with the views
  • Our goal here is to show you how the system works independently of the rest of Django.

7 of 18

  • Here is the most basic way you can use Django’s template system in Python code:
  • 1. Create a Template object by providing the raw template code as a string.
  • 2. Call the render() method of the Template object with a given set of variables (the context). This returns a fully rendered template as a string, with all of the variables and template tags evaluated according to the context.

8 of 18

>>> from django import template

>>> t = template.Template(’My name is {{ name }}.’)

>>> c = template.Context({’name’: ’kec’})

>>> print t.render(c)

My name is kec.

>>> c = template.Context({’name’: ’Fred’})

>>> print t.render(c)

My name is Fred.

9 of 18

  • Creating Template Objects
  • The easiest way to create a Template object is to instantiate it directly. The Template class lives in the django.template module, and the constructor takes one argument, the raw template code

10 of 18

  • When you create a Template object, the template system compiles the raw template code into an internal, optimized form, ready for rendering.
  • But if your template code includes any syntax errors, the call to Template() will cause a TemplateSyntaxError exception:

11 of 18

Rendering a Template

  • Once you have a Template object, you can pass it data by giving it a context.
  • A context is simply a set of template variable names and their associated values. A template uses this to populate its variables and evaluate its tags.

12 of 18

  • The term “block tag” here refers to {% notatag %}. “Block tag” and “template tag” are synonymous.
  • The system raises a TemplateSyntaxError exception for any of the following cases:
  • • Invalid tags• Invalid arguments to valid tags
  • • Invalid filters • Invalid arguments to valid filters • Invalid template syntax • Unclosed tags (for tags that require closing tags)

13 of 18

  • A context is represented in Django by the Context class, which lives in the django.template module. Its constructor takes one optional argument: a dictionary mapping variable names to variable values

14 of 18

  • from django.template import Context, Template
  • >>> t = Template(’My name is {{ name }}.’)
  • >>> c = Context({’name’: ’Stephane’})
  • >>> t.render(c)
  • u’My name is Stephane.’
  • t.render(c) is a Unicode object – not a normal

Python string

  • Django uses Unicode objects instead of normal strings throughout the framework

15 of 18

  • A Python dictionary is a mapping between known keys and variable values. A Context is similar to a dictionary, but a Context provides additional functionality
  • Variable names must begin with a letter (A-Z or a-z) and may contain more letters, digits, underscores, and dots.
  • Variable names are case sensitive.

16 of 18

Multiple Contexts, Same Template

  • >>> from django.template import Template, Context
  • >>> t = Template(’Hello, {{ name }}’)
  • >>> print t.render(Context({’name’: ’John’}))
  • Hello, John
  • >>> print t.render(Context({’name’: ’Julie’}))
  • Hello, Julie
  • >>> print t.render(Context({’name’: ’Pat’}))
  • Hello, Pat

17 of 18

  • # Bad
  • for name in (’John’, ’Julie’, ’Pat’):
  • t = Template(’Hello, {{ name }}’)
  • print t.render(Context({’name’: name}))
  • # Good
  • t = Template(’Hello, {{ name }}’)
  • for name in (’John’, ’Julie’, ’Pat’):
  • print t.render(Context({’name’: name}))

18 of 18

Context Variable Lookup