zoukankan      html  css  js  c++  java
  • 三,Smarty模板技术/引擎——变量操作(2)

    1, 变量的分类

    ① 从PHP中分配的变量,比如a.php跳转到b.php时候,可以在a.php中分配变量,b.tpl中直接调用。a.php中代码,$smarty->assign(‘str’,’hello world’);在b.tpl中代码,{$str}直接打印出hello world。

    index.php

    <?php
    require_once "./libs/Smarty.class.php";
    $smarty = new Smarty();
    $smarty->assign('str','hello world');
    $smarty->display('index.tpl');

    index.tpl

    <html>
    <body>
    <h1>显示记录</h1>
    {$str}
    <br/>
    </body>
    </html>

    ② 从配置文件中读取变量

    在项目下新建config目录,config目录下面新建配置文件my.ini。

    my.ini

    title = 'smarty显示记录'
    bgcolor = 'pink'
    

      

    index.php

    <?php
    require_once "./libs/Smarty.class.php";
    $smarty = new Smarty();
    
    $smarty->assign('str','hello world');
    $smarty->display('index.tpl');
    ?>
    

    index.tpl

    {config_load file="./config/my.ini"}
    <html>
    <body bgcolor="{#bgcolor#}">
    <h1>显示记录</h1>
    {#title#}
    <br/>
    </body>
    </html>
    

      页面打印结果

    在建立smarty对象后,可以指定配置文件路径,tpl中直接引用即可。

    index.php修改为如下样式:

    <?php
    require_once "./libs/Smarty.class.php";
    $smarty = new Smarty();
    $smarty->config_dir = './config';
    $smarty->assign('str','hello world');
    $smarty->display('index.tpl');
    ?>
    

    index.tpl样式如下:

    {config_load file="my.ini"}
    <html>
    <body bgcolor="{#bgcolor#}">
    <h1>显示记录</h1>
    {#title#}
    <br/>
    </body>
    </html>
    

    ③ Smarty保留变量,在tpl中直接获取get、post、server、session变量。我们通常是在php中获取这些变量,再通过smarty的assign属性发送给tpl。现在通过smarty的保留变量可以直接tpl中获取这些变量,当然我们不提倡这么做。

    login.php跳转到index.php,index.php通过smarty模板显示。

    login.php

    <a href="index.php?name=hello world& age=20">新页面</a>
    

    a)  旧方式

    index.php

    <?php
    require_once "./libs/Smarty.class.php";
    $smarty = new Smarty();
    
    $smarty->assign('name',$_GET['name']);
    $smarty->assign('age',$_GET['age']);
    $smarty->display('index.tpl');
    

    index.tpl

    <html>
    <body bgcolor="pink">
    <h1>显示记录</h1>
    {$name}<br/>
    {$age}
    <br/>
    </body>
    </html>

    b  新方式

    index.php

    <?php
    require_once "./libs/Smarty.class.php";
    $smarty = new Smarty();
    $smarty->display('index.tpl');
    ?>
    

    index.tpl

    <html>
    <body bgcolor="pink">
    <h1>显示记录</h1>
    {$smarty.get.name}<br/>
    {$smarty.get.age}<br/>
    
    </body>
    </html>
    

      两者输出结果一样,建议使用旧的方式。

    2,在模板文件中对引用的变量可以进行数学运算,但不能使用()改变运算的次序。

    Smarty的变量调节器,就是操作变量的函数,在tpl中引用的方式{变量调节器|字符串},比如{$title|capitalize}字符串每个单词首字母大写。我们可以自建函数,操作变量。

  • 相关阅读:
    让GoogleCode的SVN下的HTML文件在FireFox下正常显示
    添加验证控件出错
    【转载】SQLServer中char、varchar、nchar、nvarchar的区别:
    人生第一篇博客
    二叉排序树
    最小编辑距离
    面试题集锦_4
    面试题集锦_3
    键树
    B树
  • 原文地址:https://www.cnblogs.com/usa007lhy/p/4969286.html
Copyright © 2011-2022 走看看