《Django By Example》

Django学习(三)定制情书

2017-12-08  本文已影响29人  山阴少年

  在Django学习(一)一首情诗中,views.py中HTML被直接硬编码在代码之中,虽然这样便于解释视图是如何工作的,但直接将HTML硬编码到视图却不算一个好主意。因为:

  基于以上原因,Django推荐使用模板。模板(Template)是一个文本,用于分离文档的表现形式和内容。模板通常用于产生HTML.
  本次分享的目标是利用Django的模板来产生一封简单的情书。这需要用到Django模板方面的知识。
  先新建项目love_letter:

django-admin.py startproject love_letter

切换到该文件夹下的love_letter目录,新建letter.html文件,即Django的模板,代码如下:

<html>
    <head>
         <title>Love Letter</title>
    </head>
<body>
    <h1>Love Letter for {{ name }}</h1>

    <p>Dear {{ name }}:</p>

    <p>Now you are reading a letter from your BF. Thanks for reading it.</p>

    <p>We met on {{met_date}}, and today is {{today}}, so we have been together for {{days}} days.</p>

    <p>Now you live in {{your_city}}, and I live in {{my_city}}.
        {% ifequal your_city.lower my_city.lower %}
            So lucky for living in the same city!
    {% else %}
            What a pity for not being together!
        {% endifequal %}
    </p>

    <p>So glad to meet you! You must be the heaven-sent angel for you are
        <ul>
            {% for trait in traits %}
                <li>{{trait}}</li>
            {% endfor %}
        </ul>
    I'm so fascinated of you!
    </p>

    <p>
        It is now {{weather}} in {{your_city}},
        {% ifequal weather 'cold'%}
            take care of yourself.
        {% else %}
            {% ifequal weather 'hot'%}
                take care of yourself.
            {% else %}
                nice weather, isn't it?
            {% endifequal %}
        {% endifequal %}

        Hoping for seeing you soon! May you have a pleasent day!
    </p>

    <p>Yours Sincerely,<br/>{{ today }}<br/>{{ author }}</p>

</body>
</html>

  我们有必要对这个模板做解释:

  定义好模板之后,我们应该告诉Django怎样使用这个模板,因此,需要在settings.py中的TEMPLATES设置DIRS:


设置模板路径

  这样我们就能在视图中使用该模板了。在相同的文件夹下,新建views.py,代码如下:

from django.shortcuts import render_to_response
import datetime

def output(request):
    c = {'name':'Rose',
         'met_date': datetime.datetime(2016,5,24,18,0,0),
         'today': datetime.datetime.now(),
         'your_city': 'shanghai',
         'my_city': 'Shanghai',
         'traits': ['young and pretty', 'lovely and positive', 'warm-hearted and careful', 'independent and clever'],
         'weather': 'cold',
         'author': 'Jclian'
          }
    c['days'] = (c['today'] - c['met_date']).days
    return render_to_response('letter.html', c)

其中c为字典,keys为模板中定义的变量,values可以自由定义。
  最后配置好urls.py,并开启8000端口,在网页中输入localhost:8000,得到的页面如下:

定制情书


参考文献:
  1. Django中文教程.pdf:http://download.csdn.net/download/huangzhichang13/8177581
  2. Django官方文档之Templates:https://docs.djangoproject.com/en/2.0/topics/templates/
上一篇 下一篇

猜你喜欢

热点阅读