Õâ»áµ¼Ö¼¸¸öÎÊÌ⣺
1£¬ÏÔÈ»£¬ÈκÎÒ³ÃæµÄ¸Ä¶¯»áÇ£³¶µ½Python´úÂëµÄ¸Ä¶¯
ÍøÕ¾µÄÉè¼Æ¸Ä¶¯»á±ÈPython´úÂë¸Ä¶¯¸üƵ·±£¬ËùÒÔÈç¹ûÎÒÃǽ«Á½Õß·ÖÀ뿪»á¸ü·½±ã
2£¬Æä´Î£¬Ð´ºǫ́Python´úÂëÓëÉè¼ÆHTMLÊDz»Í¬µÄ¹¤×÷£¬¸üרҵµÄWeb¿ª·¢Ó¦¸Ã½«Á½Õß·Ö¿ª
Ò³ÃæÉè¼ÆÕߺÍHTML/CSS³ÌÐòÔ±²»Ó¦¸Ã±à¼Python´úÂ룬ËûÃÇÓ¦¸ÃÓëHTML´ò½»µÀ
3£¬³ÌÐòԱдPython´úÂëÍ¬Ê±Ò³ÃæÉè¼ÆÕßдHTMLÄ£°å»á¸ü¸ßЧ£¬¶ø²»ÊÇÒ»¸öÈ˵ȴýÁíÒ»¸öÈ˱à¼Í¬ÑùµÄÎļþ
Òò´Ë£¬Ê¹ÓÃDjangoµÄÄ£°åϵͳ·ÖÀëÉè¼ÆºÍPython´úÂë»á¸ü¸É¾»¸üÒ×ά»¤
Ä£°åϵͳ»ù´¡
DjangoÄ£°åÊÇÒ»¸östringÎı¾£¬ËüÓÃÀ´·ÖÀëÒ»¸öÎĵµµÄÕ¹ÏÖºÍÊý¾Ý
Ä£°å¶¨ÒåÁËplaceholderºÍ±íʾ¶àÖÖÂß¼µÄtagsÀ´¹æ¶¨ÎĵµÈçºÎÕ¹ÏÖ
ͨ³£Ä£°åÓÃÀ´Êä³öHTML£¬µ«ÊÇDjangoÄ£°åÒ²ÄÜÉú³ÉÆäËü»ùÓÚÎı¾µÄÐÎʽ
ÈÃÎÒÃÇÀ´¿´¿´Ò»¸ö¼òµ¥µÄÄ£°åÀý×Ó£º
- <html>
- <head><title>Ordering notice</title></head>
- <body>
- <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>
- {% endif %}
- <p>Sincerely,<br />{{ company }}</p>
- </body>
- </html>
Õâ¸öÄ£°å±¾ÖÊÉÏÊÇHTML£¬µ«ÊǼÐÔÓÁËһЩ±äÁ¿ºÍÄ£°å±êÇ©£º
1£¬ÓÃ{{}}°üΧµÄÊDZäÁ¿£¬Èç{{person_name}}£¬Õâ±íʾ°Ñ¸ø¶¨±äÁ¿µÄÖµ²åÈ룬ÈçºÎÖ¸¶¨ÕâЩ±äÁ¿µÄÖµÎÒÃǼ´½«ËµÃ÷
2£¬ÓÃ{%%}°üΧµÄÊÇ¿é±êÇ©£¬Èç{%if ordered_warranty%}
¿é±êÇ©µÄº¬ÒåºÜ·á¸»£¬Ëü¸æËßÄ£°åϵͳ×öһЩÊÂÇé
ÔÚÕâ¸öÀý×ÓÄ£°åÖаüº¬Á½¸ö¿é±êÇ©:for±êÇ©±íÏÖΪһ¸ö¼òµ¥µÄÑ»·½á¹¹£¬ÈÃÄ㰴˳Ðò±éÀúÿÌõÊý¾Ý
if±êÇ©Ôò±íÏÖΪÂß¼µÄifÓï¾ä
ÔÚÕâÀÉÏÃæµÄ±êÇ©¼ì²éordered_warranty±äÁ¿µÄÖµÊÇ·ñΪTrue
Èç¹ûÊÇTrue£¬Ä£°åϵͳ»áÏÔʾ{%if ordered_warranty%}ºÍ{%endif%}Ö®¼äµÄÄÚÈÝ
·ñÔò£¬Ä£°åϵͳ²»»áÏÔʾÕâЩÄÚÈÝ
Ä£°åϵͳҲ֧³Ö{%else%}µÈÆäËüÂß¼Óï¾ä
3£¬ÉÏÃæ»¹ÓÐÒ»¸ö¹ýÂËÆ÷µÄÀý×Ó£¬¹ýÂËÆ÷ÊǸıä±äÁ¿ÏÔʾµÄ·½Ê½
ÉÏÃæµÄÀý×ÓÖÐ{{ship_date|date:"F j, Y"}}°Ñship_date±äÁ¿´«µÝ¸ø¹ýÂËÆ÷
²¢¸ødate¹ýÂËÆ÷´«µÝÁËÒ»¸ö²ÎÊý“F j, Y”£¬date¹ýÂËÆ÷ÒÔ¸ø¶¨²ÎÊýµÄÐÎʽ¸ñʽ»¯ÈÕÆÚ
ÀàËÆÓÚUnix£¬¹ýÂËÆ÷ʹÓùܵÀ×Ö·û“|”
DjangoÄ£°åÖ§³Ö¶àÖÖÄÚ½¨µÄ¿é±êÇ©£¬²¢ÇÒÄã¿ÉÒÔдÄã×Ô¼ºµÄ±êÇ©
ʹÓÃÄ£°åϵͳ
ÔÚPython´úÂëÖÐʹÓÃÄ£°åϵͳ£¬Çë°´ÕÕÏÂÃæµÄ²½Ö裺
1£¬ÓÃÄ£°å´úÂë´´½¨Ò»¸öTemplate¶ÔÏó
DjangoÒ²Ìṩָ¶¨Ä£°åÎļþ·¾¶µÄ·½Ê½´´½¨Template¶ÔÏó
2£¬Ê¹ÓÃһЩ¸ø¶¨±äÁ¿contextµ÷ÓÃTemplate¶ÔÏóµÄrender()·½·¨
Õ⽫·µ»ØÒ»¸öÍêÈ«äÖȾµÄÄ£°å£¬ËüÊÇÒ»¸östring£¬ÆäÖÐËùÓеıäÁ¿ºÍ¿é±êÇ©¶¼»á¸ù¾ÝcontextµÃµ½Öµ
´´½¨Ä£°å¶ÔÏó
×î¼òµ¥µÄ·½Ê½ÊÇÖ±½Ó³õʼ»¯Ëü£¬TemplateÀàÔÚdjango.templateÄ£¿éÖУ¬³õʼ»¯·½·¨ÐèÒªÒ»¸ö²ÎÊý
ÏÂÃæ½øÈëPython½»»¥»·¾³¿´¿´£º
- >>> from django.template import Template
- >>> t = Template("My name is {{my_name}}.")
- >>> print t
Ä㽫¿´µ½ÈçÏÂÐÅÏ¢
- <django.template.Template object at 0xb7d5f24c>
0xb7d5f24cÿ´Î¶¼»á¸Ä±ä£¬µ«ÊÇÎÞËùν£¬ËüÊÇTemplate¶ÔÏóµÄPython“identity”
ÔÚÕâ±¾ÊéÖУ¬ÎÒÃÇ»áÔÚPythonµÄ½»»¥Ê½»á»°»·¾³ÖÐչʾһЩʾÀý¡£µ±Äã¿´µ½Èý¸ö´óÓÚºÅ'>>>'£¬¾Í¿ÉÒÔÈ·¶¨ÊÇÔÚ½»»¥»·¾³ÖÐÁË¡£
Èç¹ûÄã´Ó±¾ÊéÖп½±´´úÂ룬¼ÇµÃ²»Òª¿½±´ÕâЩ´óÓںš£
µ±Äã´´½¨Template¶ÔÏó£¬Ä£°åϵͳ»á±àÒëÄ£°å´úÂ룬²¢×¼±¸äÖȾ
Èç¹ûÄãµÄÄ£°å´úÂëÓÐÓï·¨´íÎ󣬵÷ÓÃTemplate()·½·¨»á´¥·¢TemplateSyntaxErrorÒì³£
- >>> from django.template import Template
- >>> t = Template('{%notatag%}')
- Traceback (most recent call last):
- File "<stdin>", line 1, in ?
- ...
- django.template.TemplateSyntaxError: Invalid block tag: 'notatag'
ϵͳ´¥·¢TemplateSyntaxErrorÒì³£¿ÉÄܳöÓÚÒÔÏÂÇé¿ö£º
1£¬²»ºÏ·¨µÄ¿é±êÇ©
2£¬ºÏ·¨¿é±êÇ©½ÓÊܲ»ºÏ·¨µÄ²ÎÊý
3£¬²»ºÏ·¨µÄ¹ýÂËÆ÷
4£¬ºÏ·¨¹ýÂËÆ÷½ÓÊܲ»ºÏ·¨µÄ²ÎÊý
5£¬²»ºÏ·¨µÄÄ£°åÓï·¨
6£¬¿é±êǩû¹Ø
äÖȾģ°å
Ò»µ©ÄãÓµÓÐÒ»¸öTemplate¶ÔÏó£¬Äã¿ÉÒÔͨ¹ý¸øÒ»¸öcontextÀ´¸øËü´«µÝÊý¾Ý
contextÊÇÒ»¸ö±äÁ¿¼°¸³ÓèµÄÖµµÄ¼¯ºÏ£¬Ä£°åʹÓÃËüÀ´µÃµ½±äÁ¿µÄÖµ£¬»òÕß¶ÔÓÚ¿é±êÇ©ÇóÖµ
Õâ¸öcontextÓÉdjango.templateÄ£¿éµÄContextÀà±íʾ
ËüµÄ³õʼ»¯º¯ÊýÓÐÒ»¸ö¿ÉÑ¡µÄ²ÎÊý£ºÒ»¸öÓ³Éä±äÁ¿ÃûºÍ±äÁ¿ÖµµÄ×Öµä
ͨ¹ýcontextµ÷ÓÃTemplate¶ÔÏóµÄrender()·½·¨À´Ìî³äÄ£°å£¬ÀýÈ磺
- >>> from django.template import Context, Template
- >>> t = Template("My name is {{name}}.")
- >>> c = Context({"name": "Stephane"})
- >>> t.render(c)
- 'My name is Stephane.'
±äÁ¿Ãû±ØÐëÒÔ×Öĸ(A-Z»òa-z)¿ªÊ¼£¬¿ÉÒÔ°üº¬Êý×Ö£¬Ï»®ÏߺÍСÊýµã£¬±äÁ¿Ãû´óСдÃô¸Ð
ÏÂÃæÊÇÒ»¸öÄ£°å±àÒëºÍäÖȾµÄÀý×Ó£¬Ê¹ÓÃÕâÕ¿ªÊ¼Ê±µÄÄ£°åÀý×Ó£º
- >>> from django.template import Template, Context
- >>> raw_template = """<p>Dear {{ person_name }},</p>
- ...
- ... <p>Thanks for ordering {{ product }} from {{ company }}. It's scheduled to
- ... ship on {{ ship_date|date:"F j, Y" }}.</p>
- ...
- ... {% if ordered_warranty %}
- ... <p>Your warranty information will be included in the packaging.</p>
- ... {% endif %}
- ...
- ... <p>Sincerely,<br />{{ company }}</p>"""
- >>> t = Template(raw_template)
- >>> import datetime
- >>> c = Context({'person_name': 'John Smith',
- ... 'product': 'Super Lawn Mower',
- ... 'company': 'Outdoor Equipment',
- ... 'ship_date': datetime.date(2009, 4, 2),
- ... 'ordered_warranty': True})
- >>> t.render(c)
- "<p>Dear John Smith,</p>\n\n<p>Thanks for ordering Super Lawn Mower from Outdoor Equipment.
- It's scheduled to ship on April 2, 2009.</p>\n\n<p>Your warranty information will be included
- in the packaging.</p>\n\n\n<p>Sincerely,<br />Outdoor Equipment</p>"
ÈÃÎÒÃÇÀ´¿´¿´¶¼×öÁËЩʲô£º
1£¬ÎÒÃÇimport TemplateºÍContextÀ࣬ËüÃǶ¼ÔÚdjango.templateÄ£¿éÀïÃæ
2£¬ÎÒÃǰÑÄ£°åÎı¾´æ´¢ÔÚraw_template±äÁ¿ÀÎÒÃÇʹÓÃ"""À´¹¹½¨string£¬Ëü¿ÉÒÔ¿çÔ½¶àÐÐ
3£¬ÎÒÃÇ´´½¨Ä£°å¶ÔÏót£¬²¢¸øTemplateÀàµÄ³õʼ»¯º¯Êý´«µÝraw_template±äÁ¿
4£¬ÎÒÃÇ´ÓPythonµÄ±ê×¼¿âimport datetimeÄ£¿é£¬ÏÂÃæ»áÓõ½Ëü
5£¬ÎÒÃÇ´´½¨Ò»¸öcontext¶ÔÏóc£¬ËüµÄ³õʼ»¯º¯ÊýʹÓÃÒ»¸öÓ³Éä±äÁ¿ÃûºÍ±äÁ¿ÖµµÄ×Öµä
ÀýÈçÎÒÃÇÖ¸¶¨person_nameµÄֵΪ'John Smith'£¬productµÄֵΪ'Super Lawn Mower'µÈµÈ
6£¬×îºó£¬ÎÒÃǵ÷ÓÃÄ£°å¶ÔÏóµÄrender()·½·¨£¬²ÎÊýΪcontext¶ÔÏóc
Õ⽫·µ»ØäÖȾºóµÄÄ£°å£¬½«Ä£°åÖеıäÁ¿ÖµÌæ»»²¢¼ÆËã¿é±êÇ©µÄ½á¹û
Èç¹ûÄã¸Õ½Ó´¥Python£¬Äã¿ÉÄÜ»áÎÊΪʲôÊä³öÖаüº¬ÁËÐÂÐÐ×Ö·û'\n'¶ø²»ÊÇ»»ÐÐ
ÕâÊÇÒòΪPython½»»¥»·¾³Öе÷ÓÃt.render(c)»áÏÔʾstringµÄrepresentation¶ø²»ÊÇstringµÄÖµ
Èç¹ûÄãÏë¿´µ½»»Ðжø²»ÊÇ'\n'£¬Ê¹ÓÃprint t.render(c)¼´¿É
ÉÏÃæÊÇʹÓÃDjangoÄ£°åϵͳµÄ»ù´¡£¬Ö»ÊÇ´´½¨Ò»¸öÄ£°å¶ÔÏóºÍcontext¶ÔÏóÈ»ºóµ÷ÓÃrender()·½·¨
ͬһ¸öÄ£°å£¬¶à¸öcontextµÄÇé¿ö£º
Ò»µ©Äã´´½¨ÁËÒ»¸öÄ£°å¶ÔÏó£¬Äã¿ÉÒÔäÖȾ¶à¸öcontext£¬ÀýÈ磺
- >>> 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
ÎÞÂÛºÎʱ£¬ÄãʹÓÃͬһ¸öÄ£°åÀ´äÖȾ¶à¸öcontextµÄ»°£¬´´½¨Ò»´ÎTemplate¶ÔÏóÈ»ºóµ÷ÓÃrender()¶à´Î»á¸ü¸ßЧ
- # 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}))
DjangoµÄÄ£°å½âÎö·Ç³£¿ì£¬ÔÚºǫ́£¬´ó²¿·ÖµÄ½âÎöͨ¹ýÒ»¸öµ¥¶ÀµÄ¶ÔÕýÔò±í´ïʽµÄµ÷ÓÃÀ´×ö
ÕâÓë»ùÓÚXMLµÄÄ£°åÒýÇæÐγÉÏÊÃ÷¶Ô±È£¬XML½âÎöÆ÷±ÈDjangoµÄÄ£°åäÖȾϵͳÂýºÜ¶à
Context±äÁ¿²éÕÒ
ÉÏÃæµÄÀý×ÓÖУ¬ÎÒÃǸøÄ£°åcontext´«µÝÁ˼òµ¥µÄÖµ£¬´ó²¿·ÖÊÇstring£¬ÒÔ¼°Ò»¸ödatetime.date
¾¡¹ÜÈç´Ë£¬Ä£°åϵͳÓÅÑŵĴ¦Àí¸ü¸´ÔÓµÄÊý¾Ý½á¹¹£¬ÈçÁÐ±í£¬×ÖµäºÍ×Ô¶¨Òå¶ÔÏó
ÔÚDjangoÄ£°åϵͳÖд¦Àí¸´ÔÓÊý¾Ý½á¹¹µÄ¹Ø¼üÊÇʹÓÃ(.)×Ö·û
ʹÓÃСÊýµãÀ´µÃµ½×ÖµäµÄkey£¬ÊôÐÔ£¬¶ÔÏóµÄË÷ÒýºÍ·½·¨
ÏÂÃæÍ¨¹ýÀý×ÓÀ´½âÊÍ£¬Í¨¹ý(.)·ÃÎÊ×ÖµäµÄkey£º
- >>> from django.template import Template, Context
- >>> person = {'name': 'Sally', 'age': '43'}
- >>> t = Template('{{ person.name }} is {{ person.age }} years old.')
- >>> c= Context({'person': person})
- >>> t.render(c)
- 'Sally is 43 years old.'
ͨ¹ý(.)À´·ÃÎʶÔÏóµÄÊôÐÔ£º
- >>> from django.template import Template, Context
- >>> import datetime
- >>> d = datetime.date(1993, 5, 2)
- >>> d.year
- 1993
- >>> d.month
- 5
- >>> d.day
- 2
- >>> t = Template('The month is {{ date.month }} and the year is {{ date.year }}.')
- >>> c = Context({'date': d})
- >>> t.render(c)
- 'The month is 5 and the year is 1993.'
ÏÂÃæµÄÀý×ÓʹÓÃÒ»¸ö×Ô¶¨ÒåÀࣺ
- >>> from django.template import Template, Context
- >>> class Person(object):
- ... def __init__(self, first_name, last_name):
- ... self.first_name, self.last_name = first_name, last_name
- >>> t = Template('Hello, {{ person.first_name }} {{ person.last_name }}.')
- >>> c = Context({'person': Person('John', 'Smith')})
- >>> t.render(c)
- 'Hello, John Smith.'
СÊýµãÒ²¿ÉÒÔÓÃÀ´µ÷ÓÃÁбíµÄË÷Òý£º
- >>> from django.template import Template, Context
- >>> t = Template('Item 2 is {{ items.2 }}.')
- >>> c = Contexst({'items': ['apples', 'bananas', 'carrots']})
- >>> t.render(c)
- 'Item 2 is carrots.'
¸ºÊýµÄÁбíË÷ÒýÊDz»ÔÊÐíµÄ£¬ÀýÈçÄ£°å±äÁ¿{{ items.-1 }}½«´¥·¢TemplateSyntaxError
×îºóСÊýµã»¹¿ÉÒÔÓÃÀ´·ÃÎʶÔÏóµÄ·½·¨£¬ÀýÈçPythonµÄstringÓÐupper()ºÍisdigit()·½·¨£º
- >>> from django.template import Template, Context
- >>> t = Template('{{ var }} -- {{var.upper }} -- {{ var.isdigit }}')
- >>> t.render(Context({'var': 'hello'}))
- 'hello -- HELLO -- False'
- >>> t.render(Context({'var': '123'}))
- '123 - 123 - True'
×¢Ò⣬µ÷Ó÷½·¨Ê±Äã²»ÄܼÓÀ¨ºÅ£¬ÄãÒ²²»Äܸø·½·¨´«µÝ²ÎÊý
ÄãÖ»Äܵ÷ÓÃûÓвÎÊýµÄ·½·¨£¬ºóÃæÎÒÃÇ»á½âÊÍÕâЩ
×ܽáһϣ¬µ±Ä£°åϵͳÓöµ½±äÁ¿ÃûÀïÓÐСÊýµãʱ»á°´ÒÔÏÂ˳Ðò²éÕÒ£º
1£¬×Öµä²éÕÒ£¬Èçfoo["bar"]
2£¬ÊôÐÔ²éÕÒ£¬Èçfoo.bar
3£¬·½·¨µ÷Óã¬Èçfoo.bar()
3£¬ÁбíµÄË÷Òý²éÕÒ£¬Èçfoo[bar]
СÊýµã¿ÉÒԶ༶×ÝÉî²éѯ£¬ÀýÈç{{ person.name.upper }}±íʾ×Öµä²éѯperson['name']È»ºóµ÷ÓÃupper()·½·¨
- >>> from django.template import Template, Context
- >>> person = {'name': 'Sally', 'age': '43'}
- >>> t = Template('{{ person.name.upper }} is {{ person.age }} years old.')
- >>> c = Context({'person': person})
- >>> t.render(c)
- 'SALLY is 43 years old.'
¹ØÓÚ·½·¨µ÷ÓÃ
·½·¨µ÷ÓÃÒª±ÈÆäËûµÄ²éѯÉÔ΢¸´ÔÓÒ»µã£¬ÏÂÃæÊÇÐèÒª¼ÇסµÄ¼¸µã£º
1£¬ÔÚ·½·¨²éѯµÄʱºò£¬Èç¹ûÒ»¸ö·½·¨´¥·¢ÁËÒì³££¬Õâ¸öÒì³£»á´«µÝ´Ó¶øµ¼ÖÂäÖȾʧ
°Ü£¬µ«ÊÇÈç¹ûÒì³£ÓÐÒ»¸öֵΪTrueµÄsilent_variable_failureÊôÐÔ£¬Õâ¸ö±äÁ¿»áäÖȾ³É¿Õstring£º
- >>> t = Template("My name is {{ person.first_name }}.")
- >>> class PersonClas3:
- ... def first_name(self):
- ... raise AssertionError, "foo"
- >>> p = PersonClass3()
- >>> t.render(Context({"person": p}))
- Traceback (most recent call last):
- ...
- AssertionError: foo
- >>> class SilentAssetionError(AssertionError):
- ... silent_variable_failure = True
- >>> class PersonClass4:
- ... def first_name(self):
- ... raise SilentAssertionError
- >>> p = PersonClass4()
- >>> t.render(Context({"person": p}))
- "My name is ."
2£¬·½·¨µ÷Óýö½öÔÚËüûÓвÎÊýʱÆð×÷Ó㬷ñÔòϵͳ½«¼ÌÐø²éÕÒÏÂÒ»¸öÀàÐÍ(ÁбíË÷Òý²éѯ)
3£¬ÏÔȻһЩ·½·¨Óи±×÷Óã¬ÈÃϵͳ·ÃÎÊËüÃÇÊǺÜÓÞ´ÀµÄ£¬¶øÇҺܿÉÄÜ»áÔì³É°²È«ÐÔÎÊ
Ìâ¡£
ÀýÈçÄãÓÐÒ»¸öBankAccount¶ÔÏ󣬸öÔÏóÓÐÒ»¸ödelete()·½·¨£¬Ä£°åϵͳ²»Ó¦¸ÃÔÊÐí×öÏÂÃæµÄÊÂÇé
I will now delete this valuable data. {{ account.delete }}
ΪÁË·ÀÖ¹ÕâÖÖ×´¿ö£¬¿ÉÒÔÔÚ·½·¨ÀïÉèÖÃÒ»¸ö·½·¨ÊôÐÔalters_data
Èç¹ûÉèÖÃÁËalters_data=TrueµÄ»°Ä£°åϵͳ¾Í²»»áÖ´ÐÐÕâ¸ö·½·¨£º
- def delete(self):
- # Delete the account
- delete.alters_data = True
²»ºÏ·¨µÄ±äÁ¿ÔõÑù´¦Àí
ĬÈÏÇé¿öÏÂÈç¹û±äÁ¿²»´æÔÚ£¬Ä£°åϵͳ»á°ÑËüäÖȾ³É¿Õstring£¬ÀýÈ磺
- >>> from django.template import Template, Context
- >>> t = Template('Your name is {{ name }}.')
- >>> t.render(Context())
- 'Your name is .'
- >>> t.render(Context({'var': 'hello'}))
- 'Your name is .'
- >>> t.render(Context({'NAME': 'hello'}))
- 'Your name is .'
- >>> t.render(Context({'Name': 'hello'}))
- 'Your name is .'
ϵͳ»á¾²ÇÄÇĵØÏÔʾ´íÎóµÄÒ³Ãæ£¬¶ø²»ÊDzúÉúÒ»¸öÒì³££¬ÒòΪÕâÖÖÇé¿öͨ³£ÊÇÈËΪµÄ´íÎó¡£
ÔÚÏÖʵÇéÐÎÏ£¬Ò»¸öwebÕ¾µãÒòΪһ¸öÄ£°å´úÂëÓï·¨µÄ´íÎó¶ø±äµÃ²»¿ÉÓÃÊDz»¿É½ÓÊܵġ£
ÎÒÃÇ¿ÉÒÔͨ¹ýÉèÖÃDjangoÅäÖøü¸ÄDjangoµÄȱʡÐÐΪ£¬µÚ10ÕÂÀ©Õ¹Ä£°åÒýÇæ»áÎÒÃÇ»áÌÖÂÛÕâ¸ö
ÍæÍæContext¶ÔÏó
´ó¶àÊýÇé¿öÏÂÄã³õʼ»¯Context¶ÔÏó»á´«µÝÒ»¸ö×ֵ䏸Context()
Ò»µ©Äã³õʼ»¯ÁËContext£¬Äã¿ÉÒÔʹÓñê×¼Python×ÖµäÓï·¨Ôö¼õContext¶ÔÏóµÄitems£º
- >>> from django.template import Context
- >>> c = Context({"foo": "bar"})
- >>> c['foo']
- 'bar'
- >>> del c['foo']
- >>> c['foo']
- ''
- >>> c['newvariable'] = 'hello'
- >>> c['newvariable']
- 'hello'
Context¶ÔÏóÊÇÒ»¸östack£¬Äã¿ÉÒÔpush()ºÍpop()
Èç¹ûÄãpop()µÄÌ«¶àµÄ»°Ëü½«´¥·¢django.template.ContextPopException£º
- >>> c = Context()
- >>> c['foo'] = 'first level'
- >>> c.push()
- >>> c['foo'] = 'second level'
- >>> c['foo']
- 'second level'
- >>> c.pop()
- >>> c['foo']
- 'first level'
- >>> c['foo'] = 'overwritten'
- >>> c['foo']
- 'overwritten'
- >>> c.pop()
- Traceback (most recent call last):
- ...
- django.template.ContextPopException
µÚ10ÕÂÄã»á¿´µ½Ê¹ÓÃContext×÷Ϊstack×Ô¶¨ÒåÄ£°å±êÇ©
Ä£°å±êÇ©ºÍ¹ýÂËÆ÷»ù´¡
ÎÒÃÇÒѾÌᵽģ°åϵͳʹÓÃÄÚ½¨µÄ±êÇ©ºÍ¹ýÂËÆ÷
ÕâÀïÎÒÃÇ¿´¿´³£¼ûµÄ£¬¸½Â¼6°üº¬ÁËÍêÕûµÄÄÚ½¨±êÇ©ºÍ¹ýÂËÆ÷£¬Äã×Ô¼ºÊìϤÄǸöÁбíÀ´Á˽â¿ÉÒÔ×öʲôÊǸöºÃÖ÷Òâ
if/else
{% if %}±êÇ©¼ÆËãÒ»¸ö±äÁ¿Öµ£¬Èç¹ûÊÇ“true”£¬¼´Ëü´æÔÚ¡¢²»Îª¿Õ²¢ÇÒ²»ÊÇfalseµÄbooleanÖµ
ϵͳÔò»áÏÔʾ{% if %}ºÍ{% endif %}¼äµÄËùÓÐÄÚÈÝ£º
- {% if today_is_weekend %}
- <p>Welcome to the weekend!</p>
- {% else %}
- <p>Get back to work.</p>
- {% endif %}
{% if %}±êÇ©½ÓÊÜand£¬or»òÕßnotÀ´²âÊÔ¶à¸ö±äÁ¿Öµ»òÕß·ñ¶¨Ò»¸ö¸ø¶¨µÄ±äÁ¿£¬ÀýÈ磺
- {% if athlete_list and coach_list %}
- Both athletes and coaches are available.
- {% endif %}
- {% if not athlete_list %}
- There are no athletes.
- {% endif %}
- {% if athlete_list or coach_list %}
- There are some athletes or some coaches.
- {% endif %}
- {% if not athlete_list or coach_list %}
- There are no athletes or there are some coaches.
- {% endif %}
- {% if athlete_list and not coach_list %}
- There are some athletes and absolutely no coaches.
- {% endif %}
{% if %}±êÇ©²»ÔÊÐíͬһ±êÇ©Àïͬʱ³öÏÖandºÍor£¬·ñÔòÂß¼ÈÝÒײúÉúÆçÒ壬ÀýÈçÏÂÃæµÄ±êÇ©ÊDz»ºÏ·¨µÄ£º
- {% if athlete_list and coach_list or cheerleader_list %}
Èç¹ûÄãÏë½áºÏandºÍorÀ´×ö¸ß¼¶Âß¼£¬Ö»ÐèʹÓÃǶÌ×µÄ{% if %}±êÇ©¼´¿É£º
- {% if athlete_list %}
- {% if coach_list or cheerleader_list %}
- We have athletes, and either coaches or cheerleaders!
- {% endif %}
- {% endif %}
¶à´ÎʹÓÃͬһ¸öÂß¼·ûºÅÊǺϷ¨µÄ£º
- {% if athlete_list or coach_list or parent_list or teacher_list %}
ûÓÐ{% elif %}±êÇ©£¬Ê¹ÓÃǶÌ×µÄ{% if %}±êÇ©¿ÉÒÔ×öµ½Í¬ÑùµÄÊÂÇ飺
- {% if athlete_list %}
- <p>Here are the athletes: {{ athlete_list }}.</p>
- {% else %}
- <p>No athletes are available.</p>
- {% if coach_list %}
- <p>Here are the coaches: {{ coach_list }}.</p>
- {% endif %}
- {% endif %}
È·ÈÏʹÓÃ{% endif %}À´¹Ø±Õ{% if %}±êÇ©£¬·ñÔòDjango´¥·¢TemplateSyntaxError
for
{% for %}±êÇ©ÔÊÐíÄ㰴˳Ðò±éÀúÒ»¸öÐòÁÐÖеĸ÷¸öÔªËØ
PythonµÄforÓï¾äÓ﷨Ϊfor X in Y£¬XÊÇÓÃÀ´±éÀúYµÄ±äÁ¿
ÿ´ÎÑ»·Ä£°åϵͳ¶¼»áäÖȾ{% for %}ºÍ{% endfor %}Ö®¼äµÄËùÓÐÄÚÈÝ
ÀýÈ磬ÏÔʾ¸ø¶¨athlete_list±äÁ¿À´ÏÔʾathleteÁÐ±í£º
- <ul>
- {% for athlete in athlete_list %}
- <li>{{ athlete.name }}</li>
- {% endfor %}
- </ul>
ÔÚ±êÇ©ÀïÌí¼ÓreversedÀ´·´ÐòÑ»·ÁÐ±í£º
- {% for athlete in athlete_list reversed %}
- ...
- {% endfor %}
- {% for %}±êÇ©¿ÉÒÔǶÌ×£º
- {% for country in countries %}
- <h1>{{ country.name }}</h1>
- <ul>
- {% for city in country.city_list %}
- <li>{{ city }}</li>
- {% endfor %}
- </ul>
- {% endfor %}
ϵͳ²»Ö§³ÖÖжÏÑ»·£¬Èç¹ûÄãÏëÕâÑù£¬Äã¿ÉÒԸıäÄãÏë±éÀúµÄ±äÁ¿À´Ê¹µÃ±äÁ¿Ö»°üº¬ÄãÏë±éÀúµÄÖµ
ÀàËÆµÄ£¬ÏµÍ³Ò²²»Ö§³ÖcontinueÓï¾ä£¬±¾ÕºóÃæµÄ“ÕÜѧºÍÏÞÖÆ”»á½âÊÍÉè¼ÆµÄÔÔò
{% for %}±êÇ©ÄÚÖÃÁËÒ»¸öforloopÄ£°å±äÁ¿£¬Õâ¸ö±äÁ¿º¬ÓÐһЩÊôÐÔ¿ÉÒÔÌṩ¸øÄãһЩ¹ØÓÚÑ»·µÄÐÅÏ¢
1£¬forloop.counter±íʾѻ·µÄ´ÎÊý£¬Ëü´Ó1¿ªÊ¼¼ÆÊý£¬µÚÒ»´ÎÑ»·ÉèΪ1£¬ÀýÈ磺
- {% for item in todo_list %}
- <p>{{ forloop.counter }}: {{ item }}</p>
- {% endfor %}
2£¬forloop.counter0ÀàËÆÓÚforloop.counter£¬µ«ËüÊÇ´Ó0¿ªÊ¼¼ÆÊý£¬µÚÒ»´ÎÑ»·ÉèΪ0
3£¬forloop.revcounter±íʾѻ·ÖÐʣϵÄitemsÊýÁ¿£¬µÚÒ»´ÎÑ»·Ê±ÉèΪitems×ÜÊý£¬×îºóÒ»´ÎÉèΪ1
4£¬forloop.revcounter0ÀàËÆÓÚforloop.revcounter£¬µ«ËüÊDZíʾµÄÊýÁ¿ÉÙÒ»¸ö£¬¼´×îºóÒ»´ÎÑ»·Ê±ÉèΪ0
5£¬forloop.firstµ±µÚÒ»´ÎÑ»·Ê±ÖµÎªTrue£¬ÔÚÌØ±ðÇé¿öϺÜÓÐÓÃ
°²»ÕлªµçÄÔѧУרҵְҵ¹æ»®Ê¦ÎªÄãÌṩ¸ü¶à°ïÖú¡¾ÔÚÏß×Éѯ¡¿