[举重若轻]python+django+mysql web开发入门学习之动态模板

很多时候,我们要将后台处理的数据回显到页面上,显然用纯静态的html不可能实现,需要与一种模板语言结合,来实现动态回显,在django中内置有这样的动态模板,比如我们之前的hello world,我们可以如下改造:

from django.http import HttpResponse
from django.template import Context, Template

def hello(request):
   t = Template("hello {{ name }}")
   c = Context({"name": "world"})
   return HttpResponse(t.render(c))

先创建一个模板,这个模板里会有一个变更name,然后在模板数据里放入一个key为name,value为world的对象。然后执行t.render(c)来将模板渲染好,最终显示hello world

一般在web开发中,我们会将所有的模板文件放到一个地方,然后将后台处理好要回显的数据放到context中,然后将最终将二者渲染好,返回给浏览器显示。我们可以将不同页面的模板放在不同的文件里,通过一个接口取得这个文件,然后生成一个template。

比如我们在mysite下建一个文件夹template,存放一个hello.html文件,然后hello.html的内容即为:"hello {{ name }}"。要取到这个文件的生成模板,首先我们要在settings.py中设置TEMPLATE_DIR的值,找到TEMPLATE_DIR配置的地方,加上一行指定template路径,如下:

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.
    "PATH/template",
)

然后我们就可以将原来的views.py文件改为如下来显示内容:

from django.http import HttpResponse
from django.template import Context, Template, loader

def hello(request):
   t = loader.get_template("hello.html")
   c = Context({"name": "world"})
   return HttpResponse(t.render(c))

其它的或者可以通过loader下的render_to_string函数来执行,如下:

from django.http import HttpResponse
from django.template.loader import render_to_string

def hello(request):
    html=render_to_string('hello.html', { 'name': 'world' })
    return HttpResponse(html)

动态模板语言学习详见: https://docs.djangoproject.com/en/1.4/topics/templates/


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值