Sunday, January 8, 2017

Django - 020 - 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. Let us dip into Python interactive interpreter to see how this works in code. From the myD3site project directory type python manage.py shell to start the interactive interpreter.

Let us go through some template system basics:
~/Documents/my_d3_project/django/myD3site $ python manage.py shell
Python 2.7.10 |Anaconda 2.3.0 (64-bit)| (default, May 28 2015, 17:02:03) 
Type "copyright", "credits" or "license" for more information.

IPython 3.2.0 -- An enhanced Interactive Python.
Anaconda is brought to you by Continuum Analytics.
Please check out: http://continuum.io/thanks and https://anaconda.org
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: from django.template import Template

In [2]: t = Template("My name is {{name}}.")

In [3]: print t
<django.template.base.Template object at 0x7ffb203109d0>

In [4]: 


The 0x7ffb203109d0 will be different everytime, and it is not relevant; it is a Python thing (the Python "identity" of the Template object, if you must know.)

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:

In [1]: from django.template import Template

In [2]: t = Template('{% notatag %}')
---------------------------------------------------------------------------
TemplateSyntaxError                       Traceback (most recent call last)
<ipython-input-2-fdd5f59f5346> in <module>()
----> 1 t = Template('{% notatag %}')
TemplateSyntaxError: Invalid block tag on line 1: 'notatag'. Did you forget to register or load this tag?

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)



No comments:

Post a Comment