Note: The python version is 3.3.1, the Django version is 1.5.1, and the operating system is Windows 7. There are some differences in other versions. Readers can explore by themselves.
You may have discovered this problem in the previous chapter, that is, when the view returns text, the HTML code is hard-coded in the python code. Such as %s and so on. Writing like this often makes the program more complicated, and it becomes very troublesome once modified. Moreover, HTML code programmers may not necessarily know Python code. Current development generally separates the HTML front-end page and the Python back-end, that is, the front-end is only responsible for displaying the page. , the background is only responsible for processing data and other operations. Therefore, templates are particularly important.
So, what is a template?
A template is a text used to separate the presentation and content of a document. Templates define placeholders and various pieces of basic logic (template tags) that specify how the document should be displayed. Templates are typically used to generate HTML, but Django's templates can also generate documents in any text-based format. Let's learn what a template is from a simple example. (This example comes from DjangoBook2)
<head><title>Ordering notice</title></head> <body> <h1 id="Ordering-nbsp-notice">Ordering notice</h1> <p>Dear {{ person_name }},</p> <p>Thanks for placing an order from {{ company }}. It's scheduled to ship on {{ ship_date|date:"F j, Y" }}.</p> <p>Here are the items you've ordered:</p> <ul> {% for item in item_list %} <li>{{ item }}</li> {% endfor %} </ul> {% if ordered_warranty %} <p>Your warranty information will be included in the packaging.</p> {% else %} <p>You didn't order a warranty, so you're on your own when the products inevitably stop working.</p> {% endif %} <p>Sincerely,<br />{{ company }}</p> </body> </html>
As shown above, the way to replace python code with {{...}} or {%...%} is template, Like the first {{person_name}} is actually a variable, and {%for....%} or {% if...%} are loops. Without delving into the meaning of the above code, let's learn how to use it step by step.
>>> 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.
When you see the above code, you may be impatient to try it, but an error occurs on the second line. Generally speaking, the only error that may occur is: 'DJANGO_SETTINGS_MODULE' error. This is because when Django searches for the DJANGO_SETTINGS_MODULE environment variable, it is set in settings.py, and starting the python shell directly will cause it to not know which configuration file to use. For example, assuming mysite is in your Python search path, then DJANGO_SETTINGS_MODULE should be set to: 'mysite.settings'. So in order to avoid the trouble of setting environment variables, we should start the python shell like this.
python manage.py shell
This will save you the trouble of configuring environment variables that you are not familiar with.
Let’s analyze that piece of code.
>>> from django import template #从django中导入template对象 >>> t = template.Template('My name is {{ name }}.') #使用template对象的Template()方法 >>> c = template.Context({'name': 'Adrian'}) #使用template对象的Context()函数给赋值,比如name的值就是Adrian,Context()的()里面是一个字典 >>> print(t.render(c)) #渲染模板,也就是讲Context赋值后的name的值Adrian替换上面Template()中的{{name}}并输出 My name is Adrian. >>> c = template.Context({'name': 'Fred'}) >>> print(t.render(c)) My name is Fred.
As you can see from the above example, there are three steps to using templates. 1. Call the Template function; 2. Call the Context function; 3. Call the render function. It's that simple.
Let’s talk about the Context() function through a few codes.
#代码段1: >>> from django.template import Template,Context >>> t=Template('hello,{{name}}') >>> for name in ('A','B','C'): ... print(t.render(Context({'name':name}))) ... hello,A hello,B hello,C #代码段2: >>> from django.template import Template,Context >>> person={'name':'Thunder','age':'108'} >>> t=Template('{{person.name}} is {{person.age}} years old!') >>> c=Context({'person':person})#后面的这个person是一个字典 >>> t.render(c) 'Thunder is 108 years old!' #代码段3: >>> from django.template import Template,Context >>> t=Template('Item 2 is {{items.2}}')#items.2的意思是调用items列表的第3个元素,因为列表的索引是从0开始的 >>> c=Context({'items':['Apple','Banana','Orange']}) >>> t.render(c) 'Item 2 is Orange'
Note: items.2 above cannot be items.-1 or any other negative index.
Take a good look at the three pieces of code above. Are you just drawing inferences? Also by default, if a variable does not exist, the template system will display it as an empty string and do nothing to indicate failure.

TomergelistsinPython,youcanusethe operator,extendmethod,listcomprehension,oritertools.chain,eachwithspecificadvantages:1)The operatorissimplebutlessefficientforlargelists;2)extendismemory-efficientbutmodifiestheoriginallist;3)listcomprehensionoffersf

In Python 3, two lists can be connected through a variety of methods: 1) Use operator, which is suitable for small lists, but is inefficient for large lists; 2) Use extend method, which is suitable for large lists, with high memory efficiency, but will modify the original list; 3) Use * operator, which is suitable for merging multiple lists, without modifying the original list; 4) Use itertools.chain, which is suitable for large data sets, with high memory efficiency.

Using the join() method is the most efficient way to connect strings from lists in Python. 1) Use the join() method to be efficient and easy to read. 2) The cycle uses operators inefficiently for large lists. 3) The combination of list comprehension and join() is suitable for scenarios that require conversion. 4) The reduce() method is suitable for other types of reductions, but is inefficient for string concatenation. The complete sentence ends.

PythonexecutionistheprocessoftransformingPythoncodeintoexecutableinstructions.1)Theinterpreterreadsthecode,convertingitintobytecode,whichthePythonVirtualMachine(PVM)executes.2)TheGlobalInterpreterLock(GIL)managesthreadexecution,potentiallylimitingmul

Key features of Python include: 1. The syntax is concise and easy to understand, suitable for beginners; 2. Dynamic type system, improving development speed; 3. Rich standard library, supporting multiple tasks; 4. Strong community and ecosystem, providing extensive support; 5. Interpretation, suitable for scripting and rapid prototyping; 6. Multi-paradigm support, suitable for various programming styles.

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Atom editor mac version download
The most popular open source editor

Dreamweaver CS6
Visual web development tools
