再识django --模板引擎

加入模板

django自带模板,JAVAfreemarker有异曲同工之处,至于为什么要用模板,我觉得大概有2两个好处吧

一是能使代码整洁.看到一个脚本中有着一堆的HTML代码,甚至还有CSS代码,那恶心成都与代码长度成正比.

二是代码和逻辑分离使码农各自干自己的事情,互不干涉内政,将来要是页面的布局出问题了,那就不管我们逻辑码农的问题了,只要HTML码农改一下就OK了.

django中的模板就是字符串,一坨的HTML代码,加上django的标签,django的关键字标签都用“{% %}”括起来,比如{% if %}和{% endif %}这一对狗男女,还能{% if %}、{% else %}和{% endif %}玩3P.可以在之前的亚克西代码中测试一下,把hello.py修改一下,改成:

 

from  django.http  import  HttpResponse;

from  django.template  import  Context, Template;

 

def  hello(resquest , name):

    f 
=  open( ' templates\hello.html ' );

    str 
=  f.read();

    t 
=  Template(str);

    c 
=  Context({ ' name '  : name});

    html 
=  t.render(c) ;

    
return  HttpResponse(html);


 

这里导入了两个新的库

from django.template import Context, Template;

Context是用来填充一个模板的,而Template就是这个模板,str是这个模板的字符串,他从templates\hello.html中获得,hello.html中的文本如下:

 

这里我们简单的判断了一下name是不是空字符串,如果不是空字符串就表示有名字,需要填充的便用{{ name }}这样的形式,这个nameContext中获得,如果Context中没有定义这个名字,name就是空字符串。在这里,如果不是字符串不是空就输出<p>hello, friend!</p>

一个简单的模板就是这样,可以继续执行下python manage.py runserver测试下,当输入http://localhost:8000/hellovivyli/ 时输出的是hello, vivyli,当输入http://localhost:8000/hello/ 时输出的就是hello, friend!

 

and,or,not

另外在if 里面还能使用and ornot这样的关键字,为了防止我们对于andornot的顺序的混乱,据说python不让我们and or出现在同一个语句里面,霸气。

另外还有 {%for%},{%endfor%} {%ifequal%},{%ifnotequal%},{%include%}等标签

 

使用template loader

每次都创建一个Template,并且使用open导入字符串感觉会怪怪的,django提供了一个叫做template loader的东西可以方便使用。

在使用django-adim.py自动生成项目时有个setting.py的文件,需要在这里指定template目录,如

TEMPLATE_DIRS  =  (

     os.path.join(os.path.dirname(
__file__ ),  ' templates ' )          

)


这里指定了当前文件所在文件夹下的templates文件夹作为模板目录。

然后修改hello.py

from  django.http  import  HttpResponse;

from  django.template  import  Context;

from  django.template.loader  import  get_template;

 

def  hello(resquest , name):

    t 
=  get_template( ' hello.html ' );

    c 
=  Context({ ' name '  : name});

    html 
=  t.render(c) ;

    
return  HttpResponse(html);


 

可以看到可以直接使用get_template函数得到模板文件的Template对象。另外django更奇葩的是能把hello函数改成只有一行。

def  hello(resquest , name):

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


在这里要使用render_to_response需要导入django.shutcuts.render_to_response。即添加

from  django.shortcuts  import  render_to_response;


转载于:https://www.cnblogs.com/vivyli/archive/2010/03/09/1682029.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值