The Definitive Guide to Django 2nd Edition-Using the Template System

Let’s dive into Django’s template system so you can see how it works—but we’re not yet going to integrate it with the views that we created in the previous chapter. Our goal here is to show you how the system works independent of the rest of Django. (Usually you’ll use the template system within a Django view, but we want to make it clear that the template system is just a Python library that you can use anywhere, not just in Django views.)
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 con-
text). This returns a fully rendered template as a string, with all of the variables and
template tags evaluated according to the context.

In code, it looks like this:
[sourcecode language=”python”]
>>> from django import template
>>> t = template.Template(‘My name is {{ name }}.’)
>>> c = template.Context({‘name’: ‘Adrian’})
>>> print t.render(c)
My name is Adrian.
>>> c = template.Context({‘name’: ‘Fred’})
>>> print t.render(c)
My name is Fred.
[/sourcecode]
The following sections describe these steps in much more detail.

做实验是最爽的。一边看着AstroBoy,一边测试这些指令,那边厢Toby已经因为玩耍归于尘土。
而完全按照书里的语句提示:
[sourcecode language=”python”]
u@s:/path/to/django-project$ python
Python 2.6.2 (release26-maint, Apr 19 2009, 01:58:18)
[GCC 4.3.3] on linux2
Type “help”, “copyright”, “credits” or “license” for more information.
>>> from django import template
>>> t = template.Template(“My name is {{ name }}.”)
Traceback (most recent call last):
File ““, line 1, in
File “/var/lib/python-support/python2.6/django/template/__init__.py”, line 164, in __init__
if settings.TEMPLATE_DEBUG and origin is None:
File “/var/lib/python-support/python2.6/django/conf/__init__.py”, line 28, in __getattr__
self._import_settings()
File “/var/lib/python-support/python2.6/django/conf/__init__.py”, line 57, in _import_settings
raise ImportError(“Settings cannot be imported, because environment variable %s is undefined.” % ENVIRONMENT_VARIABLE)
ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.
>>>
[/sourcecode]
这是因为Django的template要与项目相关,所以要使用python manage.py shell交互测试才可以。那边阿童木要活了。BlueCore is input….
[sourcecode language=”python”]
u@s:/path/to/django-project$ python ./manage.py shell
Python 2.6.2 (release26-maint, Apr 19 2009, 01:58:18)
[GCC 4.3.3] on linux2
Type “help”, “copyright”, “credits” or “license” for more information.
(InteractiveConsole)
>>> from django import template
>>> t = template.Template(“My name is {{ name }}.”)
>>> c = template.Context({“name”: “Hello”})
>>> print t.render(c)
My name is Hello.
>>>
[/sourcecode]

打赏

发表评论

电子邮件地址不会被公开。 必填项已用*标注