zoukankan      html  css  js  c++  java
  • Django学习(二)---使用模板Templates

    学会使用渲染模板的方法来显示html内容。

    一、Templates是什么:

    HTML文件

    使用了Django模板语言(Django Tamplate Language DTL)

    可以使用第三方模板

    二、开发Template

    1.在app根目录下新建一个 templates 文件夹,里面新建一个index.html

    myblog  
    ├── blog  
    │   ├── __init__.py  
    │   ├── admin.py  
    │   ├── migrations  
    │   │   └── __init__.py  
    │   ├── models.py  
    │   ├── templates  
    │   │   └── index.html  
    │   ├── tests.py  
    │   └── views.py  
    ├── manage.py  
    └── myblog  
        ├── __init__.py  
        ├── settings.py  
        ├── urls.py  
        └── wsgi.py  

    2.在index.html 中写一些内容

    <!DOCTYPE html>  
    <html>  
    <head>  
        <title>第一个Template</title>  
    </head>  
    <body>  
    <h1>Hello world</h1>
    <h2>My Blog</h2>  
    </body>  
    </html> 

    3.在views.py中返回render()

    from django.shortcuts import render
    
    # Create your views here.
    
    def index(request):                 
        return render(request,'index.html')

    4.运行cmd启动查看效果

    三、初步使用DTL

    rander()函数的第三个参数是用来传递数据到前端的,支持dict类型参数(字典,键值对)

    该字典是后台传递到模板的参数,键为参数名

    在模板中使用{{参数名}}来直接使用

    1.在views.py中返回render()

    from django.shortcuts import render
    
    # Create your views here.
    
    def index(request):                 
        return render(request,'index.html',{'hello':'hello,my blog!'})

    2.修改index.html 中的一些内容

    <!DOCTYPE html>  
    <html>  
    <head>  
        <title>第一个Template</title>  
    </head>  
    <body>  
    <h1>Hello world</h1>
    <h2>{{hello}}</h2>  
    </body>  
    </html> 

    四、注意

    Django按照settings.py中INSTALLED_APP中的添加顺序查找templates

    不同app下templates目录下的同名html文件会造成冲突

    解决方法:

    在app的templates目录下创建以APP名为名称的目录,将html文件放在该目录下

    然后修改view.py中render函数的路径

    from django.shortcuts import render
    
    # Create your views here.
    
    def index(request):                 
        return render(request,'blog/index.html',{'hello':'hello,my blog!'})

    打开http://127.0.0.1:8000/index/ 查看效果

     

  • 相关阅读:
    用VisualSVN做项目版本控制
    jQuery 停止动画
    jQuery 效果
    jQuery 效果
    jQuery 效果
    jQuery 事件
    jQuery 选择器
    jQuery 语法(一)
    Form.ShowWithoutActivation 属性
    C#里面中将字符串转为变量名
  • 原文地址:https://www.cnblogs.com/Lovebugs/p/7157984.html
Copyright © 2011-2022 走看看