Chinaunix首页 | 论坛 | 博客
  • 博客访问: 26267221
  • 博文数量: 2065
  • 博客积分: 10377
  • 博客等级: 上将
  • 技术积分: 21525
  • 用 户 组: 普通用户
  • 注册时间: 2008-11-04 17:50
文章分类

全部博文(2065)

文章存档

2012年(2)

2011年(19)

2010年(1160)

2009年(969)

2008年(153)

分类:

2010-05-14 14:30:22

smarty模板学习笔记

模板设计者们编辑模板,组合使用html标签和模板标签去格式化这些要素的输出(html表格,背景色,字体大小,样式表,等等)

笔记:这个是VIEW层的东西包含了一些HTML标签与模板标签在里面的。

因此,程序员可以改变逻辑而不需要重新构建模板,模板设计者可以改变模板而不影响到逻辑.

有个建议:让应用程序逻辑远离模板, 页面表现逻辑远离应用程序逻辑.

笔记:是这样处理的。在Django里面我们的模板层的东西也是与视图层分离了。

Smarty的特点之一是"模板编译".
意思是Smarty读取模板文件然后用他们创建php脚本.
这些脚本创建以后将被执行. 因此并没有花费模板文件的语法解析,同时每个模板可以享受到诸如Zend加速器() 或者PHP加速器().这样的php编译器高速缓存解决方案.

笔记:我的理解就是smarty是先编译成了一段PHP脚本了。然后再去让这段PHP脚本去执行的。而且在执行的过程中能够用到PHP的加速器

 

在对smarty的这几个目录赋权限的时候需要注意:

技术提示:
chmod 770
相当安全了,它只让user "nobody" group "nobody" / 访问.
如果你要对任何人开放读取访问权限(大多是为了你自己查看文件),你可以使用 775

即需要有写的权限。要不然模板写不进去内容就报鏎

示例:

模板代码如下:

{* Smarty *}{*模板注释 每门语言都有有时间研究一下structs2.0的模板语言*}

Hello, {$name}! {*定义了一个模板变量这个值是需要经由PHP代码进行渲染*}

 

我的方法是这样的:

为了避免重复制作轮子,我将smarty的配置内容写入到一个父类。然后其他需要用到的这个均将父类给require进来即可。

父类的代码如下:

// load Smarty library

require(Smarty.class.php');

class Smarty_GuestBook extends Smarty {

   function Smarty_GuestBook() {

// Class Constructor. These automatically get set with each new instance.

//类构造函数.创建实例的时候自动配置

        $this->Smarty();

        $this->template_dir = '/web/';

        $this->compile_dir = '/web/';

        $this->config_dir = '/web/';

        $this->cache_dir = '/web/';

        $this->caching = true;

        $this->assign('app_name','Guest Book');

   }

}

将这段配置定义到了父类了!

父类写完了就可以开始去将父类的内容引入进来的!

require('guestbook/setup.php');
$smarty = new Smarty_GuestBook;
$smarty->assign('name','Porky');
$smarty->display('index.tpl');

 

笔记:以后使用smarty均是这样来调用的。写一个父类然后子类实现继承即可!

 

二、基本语法

1. 注释:{* *}

2. 函数的使用{funcname attr1="val" attr2="val"}.

   使用方法:函数名 属性名=属性值

   示例:{funcname age=”21” sex=”boy”}

3. 变量:{$name}     {contacts[row].Phone}

4. 关联数组:

这个理解起来与Django其实是一样的道理。比如说Django里面我将一个关联数组赋给一个模板的。可以依据使用元素属性来引用。

$smarty = new Smarty;
$smarty->assign('Contacts',
    array('fax' => '555-222-9876',
          'email' => 'zaphod@slartibartfast.com',
          'phone' => array('home' => '555-444-3333',
                           'cell' => '555-111-1234')));//使用了关联数组
$smarty->display('index.tpl');
模板:
{$Contacts.fax}
{$Contacts.email}
{* you can print arrays of arrays as well *}
{$Contacts.phone.home}
{$Contacts.phone.cell}
效果其实跟Django的一样。{% for ele in a.object_list%} 是不是?
5. 数组下标
可以想像成就是在操作PHP里面的数组一样的。
$smarty = new Smarty;
$smarty->assign('Contacts',
    array('555-222-9876',
          'zaphod@slartibartfast.com',
          array('555-444-3333',
                '555-111-1234')));   //引用了关联数组!
$smarty->display('index.tpl');
 
模板:
{$Contacts[0]}
{$Contacts[1]}
{* you can print arrays of arrays as well *}
{$Contacts[2][0]}
{$Contacts[2][1]}
     //
二维数组的获取内容
6. 对象
越来越喜欢它了哈哈。就跟Django一样哦。也可以渲染一个对象
name: {$person->name}
email: {$person->email}
{*
能够直接引用这个对象的属性值了*}
7. 保留对象
这个我理解起来其实就是django里面的像{{forloop.counter}}即保留对象
这里面我们的保留对象包括:
{$smarty.now} :表示当前的时间戳还可以添加过滤器哈{$smarty.now|date_format:"%Y-%m-%d %H:%M:%S"}这个过滤器与django一样!
{$smarty.const}依据这个保留对象能够直接访问PHP里面定义的常量了
{$smarty.const._MY_CONST}
{$smarty.capture} 
{$smarty.config} : 这个方法能够加载已经加载过的配置变量。即加载外部的配置文件进来
{$smarty.config.foo}               就可以加载这个变量foo
{$smarty.section} 能够访问sectio  foreach的属性
{$smarty.foreach}
{$smarty.template} 表示当前被处理的模板名称
8. 页面请求变量:MS这个好像在其他的模板语言中 我没有遇到过。模板毕竟相当于是标签所以这种有服务器相关的东西能够包含到模板确实少见。可是它就有了请看
能够获取页面请求变量get post cookies server environment session变量的例子
{$smarty.get.page}                 {*获取get里面的变量值*}
{* display the variable "page" from a form a form (POST) *}
{$smarty.post.page}              {*获取post里面的变量值*}
{* display the value of the cookie "username" *}
{$smarty.cookies.username}
{* display the server variable "SERVER_NAME" *}
{$smarty.server.SERVER_NAME}
 
{* display the system environment variable "PATH" *}
{$smarty.env.PATH}
 
{* display the php session variable "id" *}
{$smarty.session.id}
 
{* display the variable "username" from merged get/post/cookies/server/env *}
{$smarty.request.username}
 
能够直接从服务器保留变量的获取变量值!
9. 变量调节器 就是过滤器

[首字大写] {$articleTitle|capitalize}(使用方法一样的!)

[字符计数]

[连接字符串]

$smarty = new Smarty;

$smarty->assign('articleTitle', 'Psychics predict world didn't end');

$smarty->display('index.tpl');

index.tpl:

{$articleTitle|cat:" yesterday."} {*字符串的相连接*}

OUTPUT:

Psychics predict world didn't end yesterday.

        这个过滤器可能是比较重要的了

            为空变量设置一个默认值。比如说有的时候可能没有渲染到

              用于html转码,url转码,在没有转码的变量上转换单引号,十六进制转码,十六进制美化,或者javascript转码.默认是html转码 可以带参数:html htmlall url quotes hex                {$articleTitle|escape:"quotes"}

      实现模板级的正则替换功能与preg_replace()一样的!

{$articleTitle|regex_replace:"/[\r\t\n]/":" "}      将合符条件的替换掉

             去除多余的空格{$articleTitle|strip:" "}
        去除HTML标签{$articleTitle|strip_tags}

10. 尝试在模板级中使用管道。即多个过滤器
{$articleTitle|upper|spacify}
11. 内建函数

        能够加载配置文件到模板的变量里面。

示例:
{config_load file="colors.conf"}   此配置文件里面有这个变量pageTitle变量
{#pageTitle#}                      能够直接输出此变量

foreach循环是选择性的section循环.
foreach
用于遍历关联数组.
foreach
的语法比section简单的多,但是作为一个折中它只能用于简单数组.
foreach
的标签必须成对,必须的参数是fromitem.
循环的名称是字母,数字和下划线.
循环可以互相嵌套,被嵌套的循环之间的名字必须是独立的.
from
变量(通常是一个数组的值)决定循环的次数
foreachelse
from变量没有值的时候被执行

示例:

{foreach from=$custid item=curr_id}         这个在项目中实际使用过!
         id: {$curr_id}
                
遍历一个数组
{/foreach}

使用的最多的代码如下:

$smarty->assign("contacts", array(array("phone" => "1", "fax" => "2", "cell" => "3"),array("phone" => "555-4444", "fax" => "555-3333", "cell" => "760-1234")));

如何遍历上面的关联数组呢?

{foreach name=outer item=contact from=$contacts}
  {foreach key=key item=item from=$contact}
    {$key}: {$item}
  {/foreach}
{/foreach}

遍历关联数组的办法

        功能其实与php里面的include功能差不多的

{include file="header.tpl" title="Main Menu" table_bgcolor="#c0c0c0"}

笔记:这样的inclde的方式还是可以传参数过来的。即模板之间还可 以传参数

这组标签用的比较多

示例代码:

{if $name eq "Fred"}               等于号为eq
         Welcome Sir.
{elseif $name eq "Wilma"}
         Welcome Ma'am.
{else}
         Welcome, whatever you are.
{/if}
{if $name == "Fred" || $name == "Wilma"}
         ...
{/if}
{if ( $amount < 0 or $amount > 1000 ) and $volume >= #minVolAmt#}
         ...
{/if}                     实现这种逻辑的运算!
{if count($var) gt 0}     这个可以做比较处理的gt
         ...
{/if}
{* test if values are even or odd *}处理的是奇偶数
{if $var is even}
         ...
{/if}
{if $var is odd}
         ...
{/if}

 

通过使用这种标签能够实现HTML的脚本输出

{literal}

   

{/literal}

 
另外推荐一些好的custome functions
示例:
index.php:
require('Smarty.php.class');
$smarty = new Smarty;
$smarty->assign('cust_ids', array(1000,1001,1002,1003));
$smarty->assign('cust_names', array('Joe Schmoe','Jack Smith','Jane
Johnson','CHarlie Brown'));
$smarty->assign('customer_id', 1001);
$smarty->display('index.tpl');
 
{html_checkboxes values=$cust_ids checked=$customer_id output=$cust_names separator="
"}
values是用value渲染的)
经过了渲染之后的输出HTML为:
Joe Schmoe

Jane Johnson
Charlie Brown
这种写HTML就非常方便了。看来这个标签是非常强大的!
Html_options
快速生成
{html_options values=$cust_ids selected=$customer_id output=$cust_names}
生成的HTML标签为:
 
Html_radios
require('Smarty.php.class');
$smarty = new Smarty;
$smarty->assign('cust_ids', array(1000,1001,1002,1003));
$smarty->assign('cust_names', array('Joe Schmoe','Jack Smith','Jane
Johnson','Carlie Brown'));
$smarty->assign('customer_id', 1001);
$smarty->display('index.tpl');
 
模板:
{html_radios values=$cust_ids checked=$customer_id output=$cust_names separator="
"}
 
 
 
 
 
 
 
 
 
 
 
实际使用:
{foreach from = $myarray item = curr}       
   
    
    {$curr.zh_id}
    
    
      
{$curr.zh_name}
    
{/foreach}
这个标签使用得最多了。
 
 
 
 
 

 

阅读(1420) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~