Django 模板使用

  环境: python 2.7 32位,Django1.6.7,win7 64位系统

承接前2篇文章

模板加载


在mysite下新建一个templates文件夹,然后在setting.py添加以下内容:


import os.path


TEMPLATE_DIRS = (
    os.path.join(os.path.dirname(__file__), 'templates').replace('\\','/'),
)



模板编写

urls.py

from django.conf.urls import patterns, include, url
from mysite.views import hello
from books.views import current_datetime
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'mysite.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),

    url(r'^admin/', include(admin.site.urls)),
	url(r'^hello/$', hello),
	url(r'^current_datetime/$',current_datetime),
)


current_datetime.html

<html><body>It is now {{ current_date }}.</body></html>


views.py

from django.shortcuts import render
from django.template import Context
from django.template.loader import get_template
from django.http import HttpResponse
import datetime
# Create your views here.

def current_datetime(request):
	now = datetime.datetime.now()
	t = get_template('current_datetime.html')
	html = t.render(Context({'current_date':now}))
	return HttpResponse(html)

针对current_datetime改进版,使用了render_to_response()和locals()函数

def current_datetime(request):
    current_date = datetime.datetime.now()
    return render_to_response('current_datetime.html', locals())

运行python manage runserver

在浏览器输入http://127.0.0.1:8000/current_datetime/,即可看到网页 输出当前的时间


模板继承

base.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
	<title>{% block title %}{% endblock %}</title>
</head>
<body>
	<h1>My helpful timestamp site</h1>
	{% block content %}{% endblock %}
	{% block footer %}
	<hr>
	<p>Thanks for visiting my site.</p>
	{% endblock %}
</body>
</html>

current_datetime.html


{% extends "base.html" %}
{% block title %}The current time{% endblock %}

{% block content %}
<p>It is now {{ current_date }}.</p>
{% endblock %}


在上面的例子中,current_datetime.html中通过extents 继承了base.html,这样在current_datetime.html中只需要修改自己感兴趣的block,就可以生成完整的网页



你可能感兴趣的:(Django 模板使用)