Sunday, January 8, 2017

Django - 019 - Using the template system

A Django project can be configured with one or several template engines (or even zero if you don't use templates). Django ships with a built in backend for its own template system the Django Template Language (DTL) . Django 1.10 also includes support for the popular alternative Jinja2 (for more information visit http://jinja.pocoo.org/). If you do not have a pressing reason to choose another backend, you should use the DTL - especially if you are writing a pluggable application and you intend to distribute templates. Django's contrib apps that include templates, like django.contrib.admin, use the DTL. 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.

In code, here is what that looks like:

~/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 import template

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

In [3]: c = template.Context({'name':'Sashank'})

In [4]: print t.render(c)
My name is Sashank.

In [5]: 

Next, let us describe each step in more detail.

Referencehttp://stackoverflow.com/questions/18081369/error-when-using-django-template

No comments:

Post a Comment