djano(2)模版

静态模版

[root@localhost app0904]# mkdir templates
[root@localhost app0904]# cd templates
[root@localhost templates]# vim home.html

<html>
<head>
  <title>test</title>
</head>
<body>
hello word!
</body>
</html>

[root@localhost app0904]# vim views.py

from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader
def main(request):
  t=loader.get_template('home.html')
  return HttpResponse(t.render())

 动态化

[root@localhost app0904]# vim views.py

from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader,Context
class Person(object):
  def __init__(self,name,age):
    self.name=name
    self.age=age

def main(request):
  t=loader.get_template('home.html')
  user={"name":"xiaoming","age":22}
  p=Person('xiaoming',12)
  li=['python','java']
  c=Context({"title":"hello word!","user":user,'person':p,'li':li})
  return HttpResponse(t.render(c))



[root@localhost templates]# vim home.html 

<html>
<head>
  <title>{{title}}</title>
</head>
<body>
hello word!i am {{user.name}},my age is {{user.age}}!!
<br />
my friend name is {{person.name}},age is {{person.age}}!!
<br />
lessons:<br />
  <li>{{li.0}}</li>
  <li>{{li.1}}</li>
</body>
</html>

Django的模板渲染(render)机制

一旦你创建一个 Template 对象,你可以用 context 来传递数据给它。 一个context 是一系列变量和它们值的集合。

t.render(c) 返回的值是一个 Unicode 对象,不是普通的 Python 字符串。 你可以通过字符串前的 u 来区分。

Django 对 Unicode 的支持,将让你的应用程序轻松地处理各式各样的字符集,而不仅仅是基本的A-Z英文字符。

捷径django.shortcuts包 

from django.shortcuts import render



class Person(object):
  def __init__(self,name,age):
    self.name=name
    self.age=age


def main(request):
  user={'name':'xiaoming','age':12}
  p=Person('xx',3)
  li=['p','a']
  return render(request,'home.html',{'title':'hello world','user':user,'person':
p,'li':li})

猜你喜欢

转载自886.iteye.com/blog/2322811