1.smarty简单运用
(1)smarty.php需要定义一些东西:
<?php date_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<?php require '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例:
(2)二维数组
(1)一维数组
<?php
$arr= array(9 => 'Tennis', 3 => 'Swimming', 8 => '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<?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