您当前的位置: 首页 >  django

嗨学编程

暂无认证

  • 0浏览

    0关注

    1405博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Django学习(3)模板定制

嗨学编程 发布时间:2019-09-17 20:52:01 ,浏览量:0

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

  • 对页面设计进行的任何改变都必须对Python代码进行相应的修改,而站点设计的修改往往比底层Python代码的修改要频繁得多。
  • Python代码编写和HTML设计是两项不同的工作,大多数专业的网站开发环境都将它们分配给不同的人员来完成。
  • 程序员编写Python代码和设计人员制作模板两项工作同时进行的效率是最高的,远胜于让一个人等待另一个人完成对某个既包含Python又包含HTML的文件的编辑工作。

基于以上原因,Django推荐使用模板。模板(Template)是一个文本,用于分离文档的表现形式和内容。模板通常用于产生HTML.

本次分享的目标是利用Django的模板来产生一封简单的情书。这需要用到Django模板方面的知识。

先新建项目love_letter:

django-admin.py startproject love_letter

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



Love Letter


Love Letter for {{ name }}

Dear {{ name }}:

Now you are reading a letter from your BF. Thanks for reading it.

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

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 %}

So glad to meet you! You must be the heaven-sent angel for you are

    {% for trait in traits %}
  • {{trait}}
  • {% endfor %}
I'm so fascinated of you!

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!

Yours Sincerely,{{ today }}{{ author }}

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

  • {{ name }}表示name变量,所有{{…}}里面包含的是变量。
  • {% ifequal your_city.lower my_city.lower %}为标签(tag),表示if判断语句,判断两个变量是否相等,需要用{% endifequal %}来结束。
  • {% for trait in traits %}为标签,表示for循环语句,traits可以为list或者set序列,需要用{% endfor %}。
  • 其余代码同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,得到的页面如下: 在这里插入图片描述

关注
打赏
1663681728
查看更多评论
立即登录/注册

微信扫码登录

0.2817s