smarty运用

来源:互联网 发布:mac怎么截图快捷键 编辑:程序博客网 时间:2024/05/16 11:36

1.smarty简单运用

(1)smarty.php需要定义一些东西:

<?phpdate_default_timezone_set("Asia/Shanghai");require 'smarty/Smarty.class.php';//加载Smarty.class.php文件define('SITE_ROOT','./tpl/');//定义一个常量$tpl = new Smarty();$tpl->template_dir = SITE_ROOT . 'template_dir';//存模板文件$tpl->compile_dir = SITE_ROOT . 'compile_dir';//存编译过的模板文件上面这两句代码为缓存需要的东西$tpl->config_dir = SITE_ROOT . 'config_dir';//存特殊配置文件$tpl->cache_dir = SITE_ROOT . 'cache_dir';//存Smarty缓存文件$tpl->caching = 1;//启用缓存$tpl->cache_lifetime = 60*60*24;//缓存时间1天$tpl->left_delimiter = '<{';//左结束符$tpl->right_delimiter = '}>';//右结束符自定义的samrty符号(2)index.php
<?phprequire 'smarty.php';$title = "title测试";$tpl->assign('a',$title);$tpl->assign('content','content测试');$tpl->display('index.phtml');(3)index.html 需要显示了
<html><head>    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />    <title>        <{$a}>    </title></head><body><{$content}></body></html>


最后出现在浏览器上的结果为
标题是:title测试
页面内容为:content测试


2.smarty中遍历函数foreach
例:
(1)一维数组
<?php
$arr 
array(=> 'Tennis'=> 'Swimming'=> 'Coding'
);
$smarty->assign('myArray'$arr
);
?>

html里写的

"{" 这个东西是可以自己定义的 例如1里面定义的"<{" 则下面"{"就需要改成"<{"

<ul>
{foreach from=$myArray key=k item=v}
<li>{$k}: {$v}</li>
{/foreach}
</ul>

最后输出
9: Tennis
3: Swimming
8: Coding

(2)二维数组
<?php
$items_list 
array(23 => array('no' => 2456'label' => 'Salad'
),
                    
96 => array('no' => 4889'label' => 'Cream'
)
                    );
$smarty->assign('items'$items_list
);
?>

<ul>
{foreach from=$items key=k item=i}
<li><a href="item.php?id={$k}">{$i.no}: {$i.label}</li>
{/foreach}
</ul>

最后输出:
<a href="item.php?id=23">2456: Salad
<a href="item.php?id=96">4889: Cream
当然href中的东西只会在浏览器地址栏里面显示出来 item.php?id=23或者96



0 0
原创粉丝点击