smarty的常用方法(一)

一、3种赋值

1、assign赋值变量

2、define赋值常量   模板中用{smarty.const.xxx}输出

3、地址栏赋值{smarty.get.xxx}

二、配置文件的引入

1、配置路径:$smarty->config_dir = './conf/';

2、在模板文件中添加配置文件:{config_load file='site.conf'}

3、输出,有2种输出方式:{$smarty.config.site}和{#site#}

三、smarty中防止标签‘{}’冲突的解决办法(2种方法)

1、在不是输出内容的前后加{literal}{/literal}  例{literal}p{background:red;}{/literal}

2、配置smarty的左右定界符,

$smarty->left_delimiter='{<';
$smarty->right_delimiter='>}';

四、assign和append

1、assign 可以用数组的方式赋值数据 例$smarty->assign(array('name'=>'huohaifeng','age'=>18));
2、append 在给同一数据赋值的时候,assign会覆盖之前的赋值,而append会已数组的形式在后面追加

五、配置信息封装(利用开开放的接口)

1、写一个继承smarty的类,然后调用这个类,此时就不用调用smarty类了(注意要引入的类引入顺序实例化的类

require '../smarty3/libs/Smarty.class.php';
//实例化
require '000.php';
$smarty=new mysmarty();

2、在新类中重写dir等一些信息 例

<?php
class mysmarty extends Smarty{
    public function __construct(){
        parent::__construct();
        
        $this->setTemplateDir('./temp');
        $this->setCompileDir('./comp');
        $this->setConfigDir('./conf');
    }
}

六、smarty中if的使用

     {if $title == 0}
     0
     {else}
     {$title}
     {/if}

七、smarty中for语句的使用

{for $i={$start} to {$end} step 2}
          {$i@last}{$i@first}&nbsp;{if $i@iteration % 3 ==0}<br/>{/if}
{
/for}

step 2 表示每次循环之后加2

从$i开始直到$end每次加2的循环

{$i@iteartion} 表示计数器,循环的次数

{$i@last}  {$i@first}  表示最后一次和第一次循环,但是到以上程序运行时,只会在第一次的和最后一次的位置输出1,是一个判断语句 可以这样用{if $i@first}hao{/if}来控制第一个和最后一个位置的输出, 但是如果是 {$i@total} 表示要循环多少次  就会在没个位置都出50。

八、smarty中foreach语句的使用

形式

      {foreach from=$cate key=k item=g}
            {$g.huo}
      {/foreach}

 九、smarty变量调节器

{$time|date_format:'%Y-%m-%d %H:%M:%S'}

 输出时间

原文地址:https://www.cnblogs.com/hhfhmf/p/4807324.html