【Django】模板文件的导入

第一步丶

在项目文件夹下创建一个装模板文件夹(templates)

把模板文件都放在这个templates文件夹里面

第二步丶

  修改views.py文件

    1.10版本之后:

from django.shortcuts import render
from django.http import  HttpResponse


# Create your views here.
def index(req):
    #return  HttpResponse('<h1>hellow word</h1>');
    return render(req,'index.html',{'name':'tom'})#导入模板的方法
                    请求参数 , 模板名称  ,  传递给模板的参数

    1.10版本之前:

from django.shortcuts  import render_to_response

def index(req):
        return render_to_response('index.html',{'name':'tom'})

第三步丶

  在模板中使用特殊符号{{}}包着键名就可以输出键的值

  例如:{{name}}就可以输出tom

 

注意:如果你需要给模板传对象信息和列表信息看如下代码

views.py:

from django.shortcuts import render
from django.http import  HttpResponse

class Person:
    def __init__(self,name,age):
        self.name=name
        self.age=age
# Create your views here.
def index(req):
    #return  HttpResponse('<h1>hellow word</h1>');
    pers=Person('',21)#对象数据
    booklist=['金典','金融','编程']#列表数据
    return render(req,'index.html',{'name':'tom','booklist':booklist,'per':pers})

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>hellow word {{name}}</h1>
    <h2>列表信息:{{booklist.0}}丶{{booklist.1}}丶{{booklist.2}}</h2>
    <h3>对象信息->名字:{{ per.name }}丶年龄:{{ per.age }}</h3>
</body>
</html>

 

  

 

posted @ 2017-07-27 17:05  丰study  阅读(485)  评论(0)    收藏  举报