Smarty学习笔记

Smarty是一个PHP的模板引擎。更明确来说,它可以帮助开发者更好地 分离程序逻辑和页面显示

一、安装

  1. 先从官网下在Smarty的压缩包,解压后,把目录下的libs文件夹拷贝到你的php项目的目录下。
    比如我的项目目录情况是这样的:
  • libs
  • templates 该目录是Smarty默认的模板存放路径
  • templates/index.tpl templates目录下的模板文件 类似于html那种
  • templates_c 该目录是Smarty默认的模板和php编译后的文件
  • index.php
    在index.php中写入以下代码:
    require "./libs/Smarty.class.php";
    $smarty = new Smarty;    // 创建一个Smarty实例
    $smarty -> assign('name', 'xiaoqiang');   // 将模板可能会用到的变量赋值到该实例化的对象中
    $smarty -> display('index.tpl'); // 内部主要靠调用this -> compiler这个函数进行编译转换展示某个模板

在index.tpl写入以下代码:

    ...
    <body>
        我的名字是{$name}
    </body>
    ...

开启php脚本后,访问本地index.php就能看到变量name被展示出来了.

二、扩展设置

在index.php中写入以下代码:

    require "./libs/Smarty.class.php";
    $smarty = new Smarty;    // 创建一个Smarty实例
    // 下面是一些常用的配置的改变
    $smarty - >template_dir = './templates/';  // 设置模板的存放位置
    $smarty - >compile_dir = './templates_c/';  // 设置编译后的文件存放的位置
    $smarty - >config_dir = './configs/';   // 设置配置文件的存放位置
    $smarty - >cache_dir = './cache/';   // 设置缓存文件的存放位置
    $smarty - >left_delimiter = '{'   // 设置左边界符
    $smarty - >right_delimiter = '}'  // 设置右边界符
    
    $smarty -> assign('name', 'xiaoqiang');   // 将模板用到的变量赋值到该实例化的对象中
    $smarty -> display('index.tpl'); // 展示某个模板

三、基础语法

1.注释

    {* 我是注释的内容 *}

2.从php中分配变量

index.php:

    ...
    $smarty -> assign('name', 'xiaoqiang');   // 将模板用到的变量赋值到该实例化的对象中
    $smarty->assign('Contacts',
     array('fax' => '555-222-9876',
     'email' => 'zaphod@slartibartfast.com',
     'phone' => array('home' => '555-444-3333',
     'cell' => '555-111-1234')));
    ...

index.tpl:

    ...
    <body>
        我的名字是{$name}
        {$Contacts.fax}<br>
        {$Contacts.email}<br>
        {$Contacts.phone.home}<br>
        {$Contacts.phone.cell}<br>
    </body>
    ...

3.Smarty中保留的php变量
index.tpl:

    ...
    <body>
        <p>当前用户名: {$smarty.get.username|cat:" yesterday."}</p>
        <p>当前密码: {$smarty.get.password}</p>
        <p>当前时间戳: {$smarty.now|date_format:"%Y/%m/%d"}</p>
        <p>{$smarty.post.page}</p>
        <p>{$smarty.cookies.username}</p>
        <p>{$smarty.server.SERVER_NAME}</p>
        <p>{$smarty.env.PATH}</p>
        <p>{$smarty.session.id}</p>
        <p>{$smarty.request.username}</p>
    </body>
    ...

4.变量的过滤器、修饰器(类似于Vue的filter)
常用的修饰器有:

    capitalize  // 将变量里的所有单词首字大写。
    count_characters  // 计算变量里的字符数
    cat  // 将cat里的值连接到给定的变量后面.
    date_format // 格式化从函数strftime()获得的时间和日期(时间戳)。
    default 为空变量设置一个默认值。当变量为空或者未分配的时候,将由给定的默认值替代输出。
    escape  // 用于html转码,url转码
    lower、upper  // 将值全部转换成大写或小写
    regex_replace  // 寻找和替换正则表达式
    replace  // 寻找内容并替换掉指定的内容
    string_format // 格式化字符串的方法.例如格式化为十进制数
    truncate  // 从字符串开始处截取某长度的字符.默认是80个.
                 你也可以指定第二个参数作为追加在截取字符串后面的文本字串.该追加字串被计算在截取长度中。
                 默认情况下,smarty会截取到一个词的末尾。
                 如果你想要精确的截取多少个字符,把第三个参数改为"true"

具体参考Smarty的手册,这里就不一一列举了。
另外,对于同一个变量,你可以使用多个修改器。它们将从左到右按照设定好的顺序被依次组合使用。使用时必须要用"|"字符作为它们之间的分隔符。

    {$articleTitle|lower|spacify|truncate}
    {$articleTitle|lower|truncate:30|spacify}
    {$articleTitle|upper|spacify|truncate:30:". . ."}

5.常用内建函数

    config_load  // 用于加载配置文件
    foreach, foreachelse  // 用于对数组进行遍历
    include  // 用于在当前模板中包含其它模板
    include_php  // 用于引入php文件
    insert // insert 函数类似欲 inluce 函数,不同之处是 insert 所包含的内容不会被缓存,每次调用该模板都会重新执行该函数.
    if,elseif,else  // 条件判断语句,与php中的类似
    ldelim,rdelim  // 输出 {或}这两个字符,类似于&nbsp;那种
    literal   // 标记使得Smarty不解析该段区域代码
    section,sectionelse // 模板的 section 用于遍历数组中的数据. section 标签必须成对出现. 必须设置 name 和 loop 属性. 名称可以是包含字母、数字和下划线的任意组合. 可以嵌套但必须保证嵌套的 name 唯一. 变量 loop (通常是数组)决定循环执行的次数. 当需要在 section 循环内输出变量时,必须在变量后加上中括号包含着的 name 变量. sectionelse 当 loop 变量无值时被执行.
    index  获取index值,比如获取section循环中的index值, {$smarty.section.customer.index}
    index_prev, index_next  // 用户获取上一个或下一个循环的值
    iteration  // iteration 不像index属性受start、step和max属性的影响,该值总是从1开始(index是从0开始的).rownum 是iteration的别名,两者等同.
    first、last  // 返回Boolean值,用于判断某个值是不是循环中的第一个值或最后一个 {$smarty.section.customer.first}  {$smarty.section.customer.last} 

6.自定义函数

    assign   assign 用于在模板被执行时为模板变量赋值. {assign var="name" value="Bob"}
    counter  用于输出一个记数过程. counter 保存了每次记数时的当前记数值
    html_checkboxes  html中的checkbox {html_checkboxes name="id" options=$cust_checkboxes checked=$customer_id separator="<br />"}
    html_image  html中的img标签  {html_image file="/path/from/docroot/pumpkin.jpg"}
    html_radios  html中的radio标签 {html_radios values=$cust_ids checked=$customer_id output=$cust_names separator="<br />"}
    html_table  html中的table{html_table loop=$data cols=4 table_attr='border="0"'}  {html_table loop=$data cols=4 tr_attr=$tr}

本篇总结参考了:

Smarty的基本使用与总结

smarty完全中文手册

Smarty官方文档

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容