ITeye博客

学习Smarty3要点记录

gbtan · 2010-06-01 18:15 · 编程语言 · HTML · CSS · PHP · UI · Web · Markdown

1.       在模板tpl中定义{2+3*4},会计算成14;

2.       {$x + $y}必须紧挨着大括号,+之间有无空格关系不大;

3.       模板tpl中可定义{$str = strlen($hello)},输出{$a};{$a = strlen("$hello")}可以加引号,还可以加{}

4.       模板tpl中定义多维数组{assign var=foo value=array(1, array(3,4), 7)},也可以{assign var=foo value=array[1, [3,4], 7]},还可以{assign var=foo value=[0=>1, 1=>[3,4], 2=>7]},调用方式{$foo[1][1]},或者{$foo.1.1},输出4;

5.       Smarty3模板tpl中支持动态的变量名{assign var=foo_3 value=[0=>1, 1=>[3,4], 2=>7, 8, 12, 79]},执行{$foo_{$x}[1][1]},输出4;

6.       支持对象链:

{$object->method1($x)->method2($y)}

在Php中定义如下:

class Test {

function f1()

    {

        echo "调用方法1.<br/>";

              return $this;

    }

    function f2()

    {

        echo "调用方法2.<br/>";

}

}

 

$t = new Test;

$smarty->assign("t", $t);

 

模板tpl中可以这样引用:

{$t->f1()->f2()}

 

7.       for语句:

{for $i=0; $i<$x; $i++}

hello, {$i}<br/>

{/for}

也可以

{for $i = 0 to 3 step 1}

hello, {$i}<br/>

{/for}

{for $i = 0 to 3}

hello, {$i@iteration}, {$i@total}, {$i@first}, {$i@last}<br/>

{/for}

{foreach $myarray as $var}...{/foreach}

{while $foo}...{/while}

 

8.       函数递归:

{function name=menu level=0}

  <ul class="level{$level}">

  {foreach $data as $entry}

    {if is_array($entry)}

      <li>{$entry@key}</li>

       {menu data=$entry level=$level+1}

    {else}

      <li>{$entry}</li>

    {/if}

  {/foreach}

  </ul>

{/function}

 

{$menu = ['item1','item2','item3' => ['item3-1','item3-2','item3-3' =>

['item3-3-1','item3-3-2']],'item4']}

 

{menu data=$menu}

 

  输出:

    * item1

    * item2

    * item3

          o item3-1

          o item3-2

          o item3-3

                + item3-3-1

                + item3-3-2

* item4

 

9.       代码块不缓存:

{nocache}...{/nocache}之间的代码永远不会缓存

 

10.   模板tpl中:

{$smarty.current_dir}输出模板当前目录

 

11.字符串直接用于smarty中:

 $smarty->display('string:This is my template, {$foo}!'); // php

{include file="string:This is my template, {$foo}!"} // template

均是直接显示出string来。

 

11.   限定变量存储:

$tpl = $smarty->createTemplate('index.tpl',$smarty);

或$tpl = $smarty->createTemplate('index.tpl')

$tpl->assign('hello',"hello world!");

 

//引用模板文件

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

 

12.   可以将在一个tpl中定义的变量的范围放大,以在其他的tpl文件中使用:

{assign var=foo value='bar'}           // no scope is specified, the default 'local'

{$foo='bar'}                        // same, local scope

{assign var=foo value='bar' scope='local'} // same, local scope

 

{assign var=foo value='bar' scope='parent'}

// Values will be available to the parent object

{$foo='bar' scope='parent'}       // (normally the calling template)

 

{assign var=foo value='bar' scope='root'} 

 // Values will be exported up to the root object, so they can

{$foo='bar' scope='root'}   // be seen from all templates using the same root.

 

{assign var=foo value='bar' scope='global'}

// Values will be exported to global variable storage,

{$foo='bar' scope='global'}    // they are available to any and all templates.

 

13.   模板继承:

parent.tpl:

<html>

  <head>

    <title>{block name='title'}My site name{/block}</title>

  </head>

  <body>

    <h1>{block name='page-title'}Default page title{/block}</h1>

    <div id="content">

      {block name='content'}

        Default content

      {/block}

    </div>

  </body>

</html>

 

child.tpl:

{extends file='parent.tpl'}

{block name='title'}

Child title

{/block}

 

grandchild.tpl:

{extends file='child.tpl'}

{block name='title'}Home - {$smarty.block.parent}{/block}

{block name='page-title'}My home{/block}

{block name='content'}

  {foreach $images as $img}

    <img src="{$img.url}" alt="{$img.description}" />

  {/foreach}

{/block}

 

We redefined all the blocks here, however in the title block we used {$smarty.block.parent},which tells Smarty to insert the default content from the parent template in its place.The content block was overriden to display the image files, and page-title has also be overriden to display a completely different title.

 

If we render grandchild.tpl we will get this:

<html>

  <head>

    <title>Home - Child title</title>

  </head>

  <body>

    <h1>My home</h1>

    <div id="content">

      <img src="/example.jpg" alt="image" />

      <img src="/example2.jpg" alt="image" />

      <img src="/example3.jpg" alt="image" />

    </div>

  </body>

</html>

评论(3)

  1. #3 楼 · vb2005xu · 2010-06-02 10:08
    
    <?php $this->_extends('admin::@sys');?>
    <?php $this->_block('contents');?>	
    
    <?php $this->_element('menu-tips','admin::@sys'); ?>	
    <table width="100%" align="center" border="0" cellspacing="0" cellpadding="0">
      <tr><td class="rightmainbody">
      <table width="100%" align="center" border="0" cellspacing="0" cellpadding="0">
        <tr class="tdbheader">
          <td colspan="2"><?php echo $current_menu['name']; ?></td>
        </tr>
        
    	<?php $this->_block('main-body');$this->_endblock(); ?>
    		
        <tr>
          <td class="tablebottom" colspan="2"></td>
        </tr>
        </table>
        </td>
      </tr>
    </table>
    <?php $this->_endblock(); ?>
    
    
  2. #2 楼 · vb2005xu · 2010-06-02 10:06

    顶级页面模板代码:

    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
            "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <meta http-equiv="Pragma" content="no-cache" />
    <?php $this->_block('head'); ?>
    	<meta name="keywords" content="" />
    	<meta name="description" content="" />
    <?php $this->_endblock(); ?>
    <meta name="copyright" content="timeinchina" />
    <meta name="author" content="iamsese,vb2005xu" />
    
    <title><?php echo xser::translate('ui/admin/title');?>
    <?php $this->_block('title');$this->_endblock(); ?></title>
    
    
    <?php stylesheet_link_tag('admin/style'); $this->_block('css'); $this->_endblock(); ?>
    
    <?php $this->_element('jsinclude','admin::dashboard'); 
    	js_include_tag('admin/app.tic.sys');
    	$this->_block('js'); $this->_endblock(); ?>
    </head>
    <body>
    <a name="TOP" id="TOP"></a>
    
    <?php $this->_element('topbar-menus','admin::default'); ?>
    <?php $this->_element('navbar-menus','admin::default'); ?>
    
    <div class="mainbody">
      <table border="0" cellspacing="0" cellpadding="0" style="width:100%;">
        <tr>
          <td valign="top" style="width:150px;">
          	<!-- left-menus -->
          	<?php $this->_element('left-menus','admin::default'); ?>
          </td>
          <td valign="top" style="width:20px;"></td>
          <td valign="top">
            <table width="100%" align="center" border="0" cellspacing="0" cellpadding="0">
            	<?php $this->_block('contents');$this->_endblock(); ?>          
            </table></td>
        </tr>
      </table>
    </div>
    
    <div class="copyright">
      <?php $this->_element('copyright','admin::default'); ?>
    </div>
    
    </body>
    </html>
    
    
  3. #1 楼 · vb2005xu · 2010-06-02 10:04

    没感觉代码有什么更好的可读性,还不如php原生代码舒服,只要规定页面上不出现业务逻辑,其实代码也挺好看的,比如: 参见我写的 xser php framework 框架的视图引擎,支持模板继承

    
    <?php $this->_extends('admin::menu@sys');?>
    <?php $this->_block('main-body');?>
    	<!-- create menu -->
    	<script>
    	var menu_creater = null ;
    	xu.ready(function(){
    		menu_creater = new tic.sys.menu.Creater();
    		menu_creater.init('fm_menu_create');
    	});
    	</script>
        
        <tr class="tablecell">
          <td valign="top">菜单类型:</td>
          <td>
          <?php
          	web_control('radioGroup','menu_type',array(
    			'items'=>array(
          			' 顶部导航菜单 ' => 1 ,' 菜单组 ' => 2 ,' 菜单项 ' => 3 ,
          		) ,
    		));		
          ?>      
          </td>
        </tr>
        
        <tr class="tablecell">
          <td colspan="2">
          <form action="<?php echo $save_url?>" method="POST" id="fm_menu_create">      
          	<div id='menuinfo'></div>
          </form>
          </td>
        </tr>
        
    <?php $this->_endblock(); ?>
    
    
    
    <table width="100%" align="center" border="0" cellspacing="0" cellpadding="0">
    <?php web_control('hidden','menu[type]',array('value' => $menu['type']));?>
    <?php
    	$menu_options = array(
    		'menu[name]' => array(
    			'ctl'=>'textbox','text'=>'菜单名称',
    			'params'=>array('size' => 35,'value'=>(isset($menu['name'])?$menu['name']:null),'class'=>"formfield"),
    			'notice_caption' => ' (说明: 菜单的显示文本) *' ,
    			'error_caption' => ''
    		),
    		'menu[udi]' => array(
    			'ctl'=>'textbox','text'=>'UDI标识',
    			'params'=>array('size' => 35,'value'=>(isset($menu['udi'])?$menu['udi']:null),'class'=>"formfield"),
    			'notice_caption' => ' (格式: namespace::controller/action@module) *' ,
    			'error_caption' => ''
    		),
    		'menu[displayorder]' => array(
    			'ctl'=>'textbox','text'=>'显示次序',
    			'params'=>array('size' => 35,'value'=>(isset($menu['displayorder'])?$menu['displayorder']:0),'class'=>"formfield",'maxLength'=>2),
    			'notice_caption' => ' (格式: 小于16的整数,默认为0)' ,
    			'error_caption' => ''
    		),
    	);
    ?>
    
    <?php if (!empty($menu_options)): ?>
    
    <?php foreach ($menu_options as $option=>$values) :?>
    <tr class="tablecell">
       <td><?php echo htmlspecialchars("{$values['text']}: "); ?></td>	
       <td>
       <?php		
    		web_control($values['ctl'],$option,$values['params']);
       		web_control('label',null,array('caption'=>$values['notice_caption'],'class'=>'yes'));
       		web_control('label',"{$option}_error",array('caption'=>$values['error_caption'],'class'=>'no')); 
       	?>
       </td>
    </tr>	
    <?php endforeach?>
    
    <tr class="tablecell">
        <td colspan="2" align="center">
        <input type="submit" value="提交" class="formbutton">
        <input type="reset" value="重置" class="formbutton"></td>
    </tr>
    
    <?php endif; ?>
    </table>
    
    

评论功能维护中,当前仅展示历史评论。