django 第二课 模板变量


url.py

urlpatterns = [
    #url(r'^admin/', include(admin.site.urls)),
url(r'^testweb/index',views.hello),
url(r'^homepage0',views.homepage0),
]

views.py 

# -*- coding: utf-8 -*-


#from django.http import HttpResponse
from django.shortcuts import render_to_response
def hello(request):
context = {}
context['hello'] = 'Hello world!'
return render(request,'hello.html',context)


class user_class(object):
def __init__(self,name,age,sex):
self.name = name;
self.age = age;
self.sex = sex;
def say(self):
return 'my name is '+ self.name
def homepage0(requset):
user = user_class('flamle',23,'male')
booklist = ['A Doll\'s House','A Farewell to Arms','A Midsumer Night\'s Dream','Adam Bede','A Thousand and One Nights']
dect = {'user':user,'booklist':booklist}
return render_to_response('homepage0.html',dect)

主要的知识点在于,view中render_to_response 入参中一字典类型,将所有的模板变量传入模板中,字典中的变量名,一定要跟模板中使用的变量名完全一致。

template

<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title> flam le home page</title>
</head>
<body>
<h1>welcome to flam le home page</h1>
<p>Django learning</p>
    <li> hello my name is {{ user.name }} </li>
    <li> i'm {{ user.age }}years old </li>
    <li> i'm a {{ user.sex }} </li>
    <p>the {{ user.name }} say {{ user.say}}</p>
    <h2>below is my favorite book list</h2>
    <li>{{ booklist.0 }}</li>
    <li>{{ booklist.1 }}</li>
    <li>{{ booklist.2 }}</li>
    <li>{{ booklist.3 }}</li>
    <li>{{ booklist.3 }}</li>
    <p>please shsre with me with your favorate bool</p>
</body>

</html>

效果图


下图分享一下pycharm Ubuntu开发效果,废话不多说,好使


猜你喜欢

转载自blog.csdn.net/u012516571/article/details/80445574