zoukankan      html  css  js  c++  java
  • django基础入门(3)django中模板

    上一节中的输入,即视图中的return HttpResponse()部分。函数中的内容为<html><body>……

    意思就是,前端文件,要每次都要手写,打印,这非常麻烦。通常,它会包括很多内容,还有js文件,css文件等。而且设计页面也不好设计,或者设计好了,再粘贴html字串,进行输出。且会发现html代码与python后台代码掺杂在一起。

    通过自定义,

    直接在视图中写。新建立视图(函数)hello_who如下:

    def hello_who(request):

        t=template.Template('hello {{name}}')

        c=template.Context({'name':'宋江'})

        return HttpResponse(t.render(c))

     

    通过创建模板,输出hellowho

    这里who的名字为中文的宋江。,如果在页面中正常显示中文,需要在settings.py中设置LANGUAGE_CODE = 'zh-cn'

    且在视图文件views.py中,第一行加入#encoding=utf-8

    使用模板

    先建立模板文件,文件名任意。模板文件就是html前台文件。与aspx页类似。先建立一个hello.html文件。如下:

    <html>

    <body>

    <div style="color:red;"><b>Hello,{{name}}</b></div>

    </body>

    </html>

    然后在视图中加载这个模板,并给变量赋值。

    视图hello_who改为:

    def hello_who(request):

        t = get_template('hello.html')

        html = t.render(Context({'name': '宋江'}))

    return HttpResponse(html)

    其中,获得模板,和呈现函数,可以利用一个函数实现,如下:
    def hello_who(request):

        return render_to_response('hello.html', {'name': '宋江'})

     

    另使用这个函数,需要引入:

    from django.shortcuts import render_to_response

    通过locals()返回所有定义的映射

    def hello_who(request):

        name= '宋江'

        return render_to_response('hello.html', locals())

    博客园大道至简

    http://www.cnblogs.com/jams742003/

    转载请注明:博客园

  • 相关阅读:
    SQLyog使用期限(治标不治本的,治本的还没找到)
    计算机系统第一章
    Netty实现远程调用RPC功能
    基于Redis实现分布式锁
    Java代理
    Java反射机制
    权限之菜单权限
    记录一次 数据库迁移 MSSQL 到MySql
    .net core2.0 使用数据库创建EF模型(db first)
    VS 函数,方法上方 引用等显示
  • 原文地址:https://www.cnblogs.com/jams742003/p/3034028.html
Copyright © 2011-2022 走看看