http://www.smarty.net/
http://smarty.php.net/manual/en/

1.配置

define("ROOTPATH",dirname(__FILE__)."/../");
        require_once("smarty/Smarty.class.php");

/**
         * Smarty Template Class Initializtion
         */
        if( @constant( "ENABLED_TPL" ) ) {
            $obj_smarty = new Smarty();
            $obj_smarty->compile_check = true; //Open Compile Check
            $obj_smarty->debugging = false;// false || DEBUG || DEBUG_TPL; //debug On-off
            $obj_smarty->template_dir = ROOT_PATH."html"; //Set Template Document Root
            $obj_smarty->compile_dir = ROOT_PATH."cache"; //Set Template Cache File Document Root
            $obj_smarty->left_delimiter = "<!!"; //Set Template Left Delimiter
            $obj_smarty->right_delimiter = "!!>"; //Set Template Right Delimiter
            /**
             * 0:Smarty默认值,表示不对模板进行缓存 
             * 1:表示Smarty将使用当前定义的cache_lifetime来决定是否结束cache
             * 2:表示Smarty将使用在cache被建立时使用cache_lifetime这个值
             * 习惯上使用true与false来表示是否进行缓存
             */
            $obj_smarty->caching = true;
            $obj_smarty->cache_lifetime = 60 * 60 * 24;//-1:缓存从不过期,0:每次执行缓存总是被重新建立 
        }

2.循环,section,sectionelse

<!!sectionelse!!> 用来表示传入的数组变量为空时对模板进行的处理。

<!!section name=one loop=$arr_result start=5 step=2 max=3 show=$show_customer_info!!> 
           <!!$arr_result[one].name!!> 
           <!!$smarty.section.one.iteration!!> //display the current loop iteration
           <!!$smarty.section.one.index!!>     //display the current loop index, starting with zero 
           <!!$smarty.section.one.first!!>     //first is set to true if the current section iteration is the first one
           <!!$smarty.section.one.last!!>      //last is set to true if the current section iteration is the last one. 
           <!!$smarty.section.one.loop!!>      //display the last index number that this section looped
           <!!$smarty.section.one.show!!>      //show is a boolean value, true or false
           <!!$smarty.section.one.total!!>     //display the number of iterations that this section will loop      
           <!!$smarty.section.name.rownum+$offset!!>//display the current loop iteration, starting with one $offset为基值
        <!!/section!!>

<!!section name=one loop=$arr_result!!>
            <input type="checkbox" name="<!!$name!!>[]" id="<!!$name!!>_<!!$smarty.section.one.index+1!!>" value="<!!$arr_result[one].value!!>" 
            <!!if ($arr_result[one].value|inarray:$arr_values) !!>checked<!!/if!!>/><!!$arr_result[one].value!!>
        <!!/section!!>

<!!section name=one loop=$arr_result!!>
            <option value="<!!$arr_result[opt].value!!>" <!!if $arr_result[one].value==$selectedvalue !!>selected<!!/if!!>><!!$arr_result[one].option!!></option>
        <!!/section!!>

表格排版 1行2列 
                <!!if $smarty.section.one.index%2 eq 0 !!>
                <!!if $smarty.section.one.index%2 eq 1 !!>

奇偶数用于斑马线效果
                <!!if $smarty.section.one.rownum%2 eq '0'!!>...<!!else!!>...<!!/if!!>

生成斑马线
                <div style="background:<!!cycle values='#F0F8FF,#F0FFFF,#FFFAF0,#F0FFF0'!!>" id="div_msg_<!!$smarty.section.one.rownum!!>">
                ...
                </div>

3.表格,html_table table_foreach

<!!html_table cols=4 table_attr=' width="95%" border="0" cellspacing="0" 
           cellpadding="2" ' tr_attr=' align="left" valign="top" ' td_attr=' width="25%" ' loop=$arr_result!!>
          
        <!!table_foreach from=$addproducts item=sam key=id cols=4 table_attr='width="100%" border="0" cellspacing="4"
        cellpadding="0"' tr_attr='' td_attr=' width="25%"align="center" valign=""'!!>
          
        <a href="<!!$sam.adurl!!>">
          <img src="upload/images/<!!$sam.adpic!!>" alt="<!!$sam.adalt!!>" 
        width="100" height="100" border="0" class='picline'></a>
        <a href="<!!$sam.adurl!!>" title="<!!$sam.adalt!!>"><!!$sam.adtitle|substrgb:'0':'20':''!!></a>

<!!/table_foreach!!>

4.包含文件,include

<!!include file="header.tpl"!!>

5.不解析,literal

<!!literal!!> 这里是js或css,模板不解析 <!!/literal!!>

6.条件判断,if,elseif,else

<!!if $name eq "Fred" and ($type eq '1' || $type eq '2')!!>
            Welcome Sir.
        <!!elseif $name eq "Wilma"!!>
            Welcome Ma'am.
        <!!else!!>
            Welcome, whatever you are.
        <!!/if!!>

"eq", "ne","neq", "gt", "lt", "lte", "le", "gte" "ge","is even","is odd",
        "is not even","is not odd","not","mod","div by","even by","odd by","==","!=",">", "<","<=",">="

7:字符替换,replace

|replace:"1":"2"      1--将被替换的字符串 2--用来替换的文本
                <!!$articleTitle|replace:"pear":"apple"!!>

8:去除Html标签,strip_tags

去除Html标签 去除在<和>之间的所有标签,包括<和>.
                <!!$articleTitle|strip_tags!!>

8:字符截取,truncate,substrgb,mbstrutf8

截取|truncate:"1":"2":"3"   1--指定截取多少字符 2--截取后加在截取词后的字符串   3--检查是否截取到词的边界 Default(false)
                <!!$articleTitle|truncate:30:"...":true!!>
                <!!$articleTitle|substrgb:"0":"23":".."!!>
                <!!$arr_story[$top18].rm_title|mbstrutf8:"0":"34":"..."!!>

<!!$arr_result[one].SP_CONTENTS|substrgb:"0":"16":"..."!!> 可以解决中文截取乱码问题

9:注释,Comments

注释
                <!!* this is a comment *!!>

10:日期格式,date_format

日期格式
                <!!$smarty.now|date_format!!>
                <!!$smarty.now|date_format:"%Y/%m/%d"!!>
                <!!$smarty.now|date_format:"%Y-%m-%d"!!>
                        %y:显示两位数字年份, 00 至 99
                        %Y:显示四位数字年份
                        %m:显示数字月份,01-31
                        %b:显示英文月份,简称
                        %B:显示英文月份,全称
                        %d 显示数字日份,01-31
                        %D 显示英文日份,简称3 个字母 Mon 到 Sun

11:日期下拉列表,html_select_date

日期下拉列表
                <!!html_select_date prefix="StartDate" start_year="-5" end_year="+5" field_order="YMD" month_format="%m" display_days=false time="$time"!!>
                time="2006-06-06" 可以给定输出想要的值

12:循环,foreach,foreachelse

选择性的section循环
                from 需要循环的数组的名称 
                item 当前元素的变量名 
                key   当前关键字的变量名
                name 访问foreache属性的foreach循环名

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

<!!foreach name=outer item=contact from=$arr_result!!>
                    <!!foreach key=key item=item from=$contact!!>
                         <!!$key!!>: <!!$item!!>
                    <!!/foreach!!>
                <!!/foreach!!>

<!!foreachelse!!> 在from变量没有值的时候被执行

13:下拉列表,html_options

输出下拉列表
                name         name of select group
                values       an array of values for dropdown
                output       an array of output for dropdown
                selected     the selected option element(s)
                options      an associative array of values and output
                        <select name=customer_id>
                            <!!html_options values=$cust_ids selected=$customer_id options=$cust_options output=$cust_names!!>
                        </select>

14:换行替换,nl2br

换行符替换成<br />
                <!!$articleTitle|nl2br!!>

15:默认值,default

当变量为空或者未分配的时候,将由给定的默认值替代输出.
                <!!$articleTitle|default:"no title"!!>

16:字符处理,capitalize,ucwords

将变量里的所有单词首字大写
                <!!$articleTitle|capitalize!!>
                <!!$articleTitle|ucwords!!>

17:字符串连接,cat

字符串连接 将cat里的值连接到给定的变量后面.
                <!!$articleTitle|cat:" yesterday."!!>

18:字符处理,strtolower

将变量里的所有单词小写.
                <!!$articleTitle|strtolower!!>

19:获取字符串,fetch

获取字符串
                $str_html = $obj_smarty->fetch("index.html");

20:capture

capture函数的作用是收集模板输出的数据到一个变量里,而不是把它们输出到页面.
        任何在 {capture name="foo"}和{/capture}之间的数据都被收到了由函数的名称属性指定的变量里($foo).
        收集的信息可以用在特殊变量$smarty里.
        例如capture.foo就收集了以上数据.如果函数没有名字属性,将使用"default".
        每个{capture}都必须对应{/capture},也不能嵌套使用capture函数
        {capture name=banner}
            1
        {/capture}
        {capture name=banner2}
            2
        {/capture}

{if $smarty.capture.banner ne ""}
            <tr>
                <td>
                    {$smarty.capture.banner}
                </td>
                <td>
                    {$smarty.capture.banner2}
                </td>
            </tr>
        {/if}
        抓取数据存放在变量中 可以在一个页面中重复使用

21:include_php,php

include_php
                在模板里加载php文件
        php
                可以直接使用php代码 相当于<?php     ?>
        <!!include_php file="phpinfo.php"!!>
        <!!php!!>
            include("phpinfo.php");
            echo date("h:i:s");
        <!!/php!!>

22:insert

使模板的一部分不被缓存
        //demo.php
                $int_cache_id = sprintf('%X', crc32("index.html"));
                if( !$obj_smarty->is_cached('index.html', $int_cache_id) ) {
                    $obj_smarty->assign("str_date",date("h:i:s"));
                }
                $obj_smarty->display("index.html",$int_cache_id);

function insert_getBanner( $arrParams ) {
                    return $arrParams["lid"]."-andy-".$arrParams["sid"];
                }

//index.html
                <!!$str_date!!>
                <!!insert name="getBanner" lid="1" sid="2" !!>

23:ldelim,rdelim

ldelim and rdelim are used for displaying the literal delimiter, in our case "{" or "}". 
        输出变量 不做解析 
                <!!ldelim!!>funcname<!!rdelim!!> is how functions look in Smarty!
        OUTPUT:
                <!!funcname!!> is how functions look in Smarty!

24:strip

去除<!!strip}<!!/strip!!>间的所有空格

25:{$smarty}保留变量

页面请求变量
        {* display value of page from URL (GET) http://www.domain.com/index.php?page=foo *}
        {$smarty.get.page}

{* display the variable "page" from a form a form (POST) *}
        {$smarty.post.page}

{* 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}

{$smarty.now}变量用于访问 当前时间戳.

可以用 date_format调节器格式化输出.
        {* use the date_format modifier to show current date and time *}
        {$smarty.now|date_format:"%Y-%m-%d %H:%M:%S"}

{$smarty.const}
        可以直接访问PHP常量.
        {$smarty.const._MY_CONST_VAL}

{$smarty.template}
        当前被处理的模板的名字

26:组合使用调节器 |
       
        <!!$articleTitle!!>
        <!!$articleTitle|upper|spacify!!>
        <!!$articleTitle|lower|spacify|truncate!!>
        <!!$articleTitle|lower|truncate:30|spacify!!>
        <!!$articleTitle|lower|spacify|truncate:30:". . ."!!>

27:fetch

抓取数据
                {* include some javascript in your template *}
                {fetch file="/export/httpd/www.domain.com/docs/navbar.js"}

{* embed some weather text in your template from another web site *}
                {fetch file="http://www.myweather.com/68502/"}

{* fetch a news headline file via ftp *}
                {fetch file="ftp://user:password@ftp.domain.com/path/to/currentheadlines.txt"}

{* assign the fetched contents to a template variable *}
                {fetch file="http://www.myweather.com/68502/" assign="weather"}
                {if $weather ne ""}
                    {$weather}
                {/if}

SMARTY核心的更多相关文章

  1. smarty核心思想 自制模板引擎

    <?php $tit = '今天下雨了,淋了半条街'; function tit($file){ //读文件 $h = file_get_contents($file); $h = str_re ...

  2. smarty汇总

    Smarty:模板技术 实现功能:前后分离. 原理:主要通过Smarty核心类实现,调用display方法,将模板文件读取,用正则进行替换,替换完保存到临时文 件,将临时文件加载到当前页面. 配置文件 ...

  3. PHP做Web开发的MVC框架(Smarty使用说明 )

    PHP做Web开发的MVC框架(Smarty使用说明 ) 一.Smarty简明教程 1.安装演示 下载最新版本的Smarty-3.1.12,然后解压下载的文件.接下来演示Smarty自带的demo例子 ...

  4. Smarty小结提纲

    Smarty:模板技术 实现功能:前后分离. 原理:主要通过Smarty核心类实现,调用display方法,将模板文件读取,用正则进行替换,替换完保存到临时文件,将临时文件加载到当前页面. 配置文件( ...

  5. Smarty模板快速入门

    文件下载 1.下载地址:http://www.smarty.net/ 2.我下载的版本是3.1.27 ,将下载的文件smarty-3.1.27.zip解压出来,然后将libs文件夹的所有文件复制到你的 ...

  6. PHP15 Smarty模板

    学习目标 Smarty基本概念 Smarty安装和配置 Smarty模板设计 Smarty流程控制 Smarty基本概念 一种模板引擎,在系统中进行预处理和过滤数据.是主流的PHP模板引擎,此外PHP ...

  7. 创建 Smarty 对象

    /* //if (!defined('INIT_NO_SMARTY')) //{ header('Cache-control: private'); header('Content-type: tex ...

  8. PHP框架_Smarty_实现登录功能

    1.项目框架 |--mvc |--data 数据 |--cache 缓存 |--template_c 模板生成目录 |--framework |--function |--function.php 功 ...

  9. PHP框架_Smarty

    目录 1.环境搭建 2.基本配置 3.Smarty变量调节器 4.Smarty条件判断 5.Smarty的循环 6.Smarty模板的引用 7.Smarty类与对象的赋值与引用 8.smarty函数插 ...

随机推荐

  1. excel隔行取数据

    .6…行数据取出来 好用的公式推荐出来 1.3.5…和2.4.6…行数据取出来 在空白单元格输入=OFFSET(A2,ROW(A2)-2,0) 或=OFFSET(A1,ROW(A1),0) #1,3, ...

  2. Dart的List比较特殊的几个API

    List里面常用的属性和方法: 常用属性: length 长度 reversed 翻转 isEmpty 是否为空 isNotEmpty 是否不为空 常用方法: add 增加 addAll 拼接数组 i ...

  3. 异步函数Demo

    private static async Task<String> IssueClientRequestAsync(string serverName, string message) { ...

  4. 【LOJ6671】EntropyIncreaser 与 Minecraft

    Orz lbt Description https://loj.ac/problem/6671 Solution

  5. Python&Selenium&pytest借助allure生成自动化测试报告

    一.摘要 本篇博文将介绍Python和Selenium进行自动化测试时,如何借助allure生成自动化测试报告 二.环境配置 首先python环境中安装pytest和pytest_allure_ada ...

  6. 下划线文字,鼠标hover小样式

    CSS样式 //不只是a标签,其他有下划线的字体也可以 a:hover{ color: #ff3100; //这里的颜色是指字体颜色不是波浪下划线效果的svg图颜色     text-decorati ...

  7. Django的 select_related 和 prefetch_related 函数对 QuerySet 查询的优化

    引言 在数据库存在外键的其情况下,使用select_related()和prefetch_related()很大程度上减少对数据库的请求次数以提高性能 1.实例准备 模型: from django.d ...

  8. python之select与selector

    select/poll/epoll的区别 I/O多路复用的本质就是用select/poll/epoll,去监听多个socket对象. 参考:Linux IO模式及 select.poll.epoll详 ...

  9. 【方法】移动端H5如何调用相册和相机上传图片、音频、视频

    在移动端上传图片方法很简单,使用HTML5中的input:file供文件上传. <一>常用属性值: 1.accept:规定文件上传来提交的文件类型,此属性只能和type:file配合使用 ...

  10. MFC 画字体DrawText()或TextOut(),CFont字体样式类

    新建单个文档的MFC应用程序,类视图——View项的属性——消息,WM_PAINT,创建OnPaint()函数 void CMFCApplication27View::OnPaint() { CPai ...