python Django模板的使用方法
作者:lijiao 发布时间:2021-06-09 15:29:14
模板是一个文本,用于分离文档的表现形式和内容。 模板定义了占位符以及各种用于规范文档该如何显示的各部分基本逻辑(模板标签)。 模板通常用于产生HTML,但是Django的模板也能产生任何基于文本格式的文档。
来一个项目说明
1、建立MyDjangoSite项目具体不多说,参考前面。
2、在MyDjangoSite(包含四个文件的)文件夹目录下新建templates文件夹存放模版。
3、在刚建立的模版下建模版文件user_info.html
<html>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>用户信息</title>
<head></head>
<body>
<h3>用户信息:</h3>
<p>姓名:{{name}}</p>
<p>年龄:{{age}}</p>
</body>
</html>
说明:{{ name }}叫做模版变量;{% if xx %} ,{% for x in list %}模版标签。
4、修改settings.py 中的TEMPLATE_DIRS
导入import os.path
添加 os.path.join(os.path.dirname(__file__), ‘templates').replace(‘\\','/'),
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
#"E:/workspace/pythonworkspace/MyDjangoSite/MyDjangoSite/templates",
os.path.join(os.path.dirname(__file__), 'templates').replace('\\','/'),
)
说明:指定模版加载路径。其中os.path.dirname(__file__)为当前settings.py的文件路径,再连接上templates路径。
5、新建视图文件view.py
#vim: set fileencoding=utf-8:
#from django.template.loader import get_template
#from django.template import Context
#from django.http import HttpResponse
from django.shortcuts import render_to_response
def user_info(request):
name = 'zbw'
age = 24
#t = get_template('user_info.html')
#html = t.render(Context(locals()))
#return HttpResponse(html)
return render_to_response('user_info.html',locals())
说明:Django模板系统的基本规则: 写模板,创建 Template 对象,创建 Context , 调用 render() 方法。
可以看到上面代码中注释部分
#t = get_template(‘user_info.html') #html = t.render(Context(locals()))
#return HttpResponse(html)
get_template(‘user_info.html'),使用了函数 django.template.loader.get_template() ,而不是手动从文件系统加载模板。 该 get_template() 函数以模板名称为参数,在文件系统中找出模块的位置,打开文件并返回一个编译好的 Template 对象。
render(Context(locals()))方法接收传入一套变量context。它将返回一个基于模板的展现字符串,模板中的变量和标签会被context值替换。其中Context(locals())等价于Context({‘name':'zbw','age':24}) ,locals()它返回的字典对所有局部变量的名称与值进行映射。
render_to_response Django为此提供了一个捷径,让你一次性地载入某个模板文件,渲染它,然后将此作为 HttpResponse返回。
6、修改urls.py
from django.conf.urls import patterns, include, url
from MyDjangoSite.views import user_info
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'MyDjangoSite.views.home', name='home'),
# url(r'^MyDjangoSite/', include('MyDjangoSite.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
# url(r'^admin/', include(admin.site.urls)),
url(r'^u/$',user_info),
)
7、启动开发服务器
基本一个简单的模版应用就完成,启动服务看效果!
效果如图:
模版的继承
减少重复编写相同代码,以及降低维护成本。直接看应用。
1、新建/templates/base.html
<html>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>{% block title %}{% endblock %}</title>
<head></head>
<body>
<h3>{% block headTitle %}{% endblock %}</h3>
{% block content %} {% endblock %}
{% block footer %}
<h3>嘿,这是继承了模版</h3>
{% endblock%}
</body>
</html>
2、修改/template/user_info.html,以及新建product_info.html
urser_info.html
{% extends "base.html" %}
{% block title %}用户信息{% endblock %}
<h3>{% block headTitle %}用户信息:{% endblock %}</h3>
{% block content %}
<p>姓名:{{name}}</p>
<p>年龄:{{age}}</p>
{% endblock %}
product_info.html
{% extends "base.html" %}
{% block title %}产品信息{% endblock %}
<h3>{% block headTitle %}产品信息:{% endblock %}</h3>
{% block content %}
{{productName}}
{% endblock %}
3、编写视图逻辑,修改views.py
#vim: set fileencoding=utf-8:
#from django.template.loader import get_template
#from django.template import Context
#from django.http import HttpResponse
from django.shortcuts import render_to_response
def user_info(request):
name = 'zbw'
age = 24
#t = get_template('user_info.html')
#html = t.render(Context(locals()))
#return HttpResponse(html)
return render_to_response('user_info.html',locals())
def product_info(request):
productName = '阿莫西林胶囊'
return render_to_response('product_info.html',{'productName':productName})
4、修改urls.py
from django.conf.urls import patterns, include, url
from MyDjangoSite.views import user_info,product_info
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'MyDjangoSite.views.home', name='home'),
# url(r'^MyDjangoSite/', include('MyDjangoSite.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
# url(r'^admin/', include(admin.site.urls)),
url(r'^u/$',user_info),
url(r'^p/$',product_info),
)
5、启动服务效果如下:


猜你喜欢
- 对图像块应用仿射变换,我们将其称为图像扭曲(或者仿射扭曲)。该操作不仅经常应用在计算机图形学中,而且经常出现在计算机视觉算法中。一、仿射变换
- 找到一句可以获得当前最新ID的语句,如下:conn.execute("insert into member (user,code)
- 1、cd /usr/local/ ##进入local目录2、cp /home/soft/MySQL-5.7.15-Linux-glibc2.
- 学习目的: 掌握文本框的用法 初次接触try…catch…语法 今天内容很轻松,用一个例子,输入年月日,判断输入是否正确 图片如下: 用个
- 1创建窗口1 turtle.setup(width,height,startx,starty)设置主窗口的大小和位置,width如果是整数,
- 根据Nicholas的说法,有四种代码会拖慢脚本的运行,并最终导致脚本失控。分别是次数过多的同步循环、庞大的函数体、不恰当的递归和不合理的D
- PYTHON 字节码设计在本篇文章当中主要给大家介绍 cpython 虚拟机对于字节码的设计以及在调试过程当中一个比较重要的字段 co_ln
- 本文实例为大家分享了Vue实现通知或详情类弹窗的具体代码,供大家参考,具体内容如下效果如图所示:(整体样式模仿ant-design-vue
- asp编程手工定义参数的方法: Dim con As ADODB.Connection
- 本文实例讲解了Python中除法使用的注意事项,是非常重要的技巧,对于Python程序设计来说有很好的借鉴价值。具体分析如下:现来看如下示例
- 一、准备工作请参照 Vue前端框架搭建 使用模板创建框架。二、创建登录页1.main.js 中引入全局 ToastPlugin、Loadin
- 前言调用,让客户端可以更具自身情况自由选择,服务端工作只需要做一份呢?还别说真还有一个准备好的轮子那就是今天的主角《grpc-gateway
- #这是Python中的一个字典 dic = { 'str': 'this is a string',
- 安装pyinstallpip install pyinstaller注意事项除非必要,否则尽量不要直接import module,用from
- 页面上有些重要内容需要提醒客户,可采用的方法有很多。提醒用户关注某一区域(div),可以给该div加上边框闪烁的效果,达到吸引用户眼球的效果
- 一.JavaScript基本介绍js诞生于1995年,是Javascript的缩写,其与java语言没有关系,当时的主要目的是验证表单的数据
- 算法思路Knuth-Morris-Pratt(KMP)算法是解决字符串匹配问题的经典算法,下面通过一个例子来演示一下:给定字符串"
- 使用django启动命令行和脚本,可以方便的使用django框架做开发,例如,数据库的操作等。下面分别介绍使用方法。django shell
- 一、安装plotly库因为这部分内容主要是用plotly库进行数据动态展示,所以要先安装plotly库pip install plotly除
- 1. 返回列表和标量(Scalar)前面我们注意到Query对象可以返回可迭代的值(iterator value),然后我们可以通过for