Djangle 模板的使用

在根目录下创建templates模板文件夹
	可以再创建子文件夹放各个应用的template

在settings中 的 templates 的 DIRS中 添加模板文件目录
'DIRS' : [ os.path.join(BASE_DIR,'template') ],

BASE_DIR 就是项目目录的绝对路径

在views.py 中使用模板文件
1. 加载模板文件
	去模板目录下获取html文件的内容 得到一个模板对象
2. 定义模板上下文
	向模板文件传递数据
3.模板渲染
	得到一个标准的html内容   把变量替换成对应的html格式

from django.template import loader
	
	def index(request):

		# 加载模板文件 模板对象
		temp = loader.get_template('booktest/index.html')
		# 定义模板上下文 给模板文件传递数据
		context = RequestContext( request, {})
		# 模板渲染 产生标准的html内容
		res_html = temp.render(context)
		# 返回给浏览器
		return HttpResponse(res_html)
	

def my_render(request,template_path,context_dict={}):
	temp = loader.get_template(template_path)
	context = RequestContext(request,context_dict)
	res_html = temp.render(context)
	return HttpResponse(res_html)

def index(request):
	return my_render(request,'booktest/index.html')

模板不仅仅是html文件 可以放变量
def index(request):
	return my_render(request,'booktest/index.html',{'content':'hello world'})
	传变量给模板文件
	
	使用模板变量
	在html文件中添加变量
	{{ content }}
	在模板文件中使用for循环
	<ul>
		{% for i in list %}
			<li> {{i}} </li>
		{% endfor %}
	</ul>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值