PHP开发中关于smarty的基础使用

来源:互联网 发布:php授权验证系统源码 编辑:程序博客网 时间:2024/06/15 22:45

在使用smarty的时候,需要提前下载smarty压缩包,我们主要需要里面的libs文件目录,把该目录拷贝到我们的项目目录下,该目录主要使用的的类文件是Smarty.class.php。

第一步  我们先创建一个Smarty.inc.php,这个文件的主要内容是对smarty的基础配置,以方便后面的使用

代码:<?php  
//首先包含Smarty类文件  
include_once('/libs/Smarty.class.php');  
//实例化Smarty类文件  
$smarty=new Smarty();  
//$smarty->cache_dir="caches";//缓存文件夹可选为减轻压力  
//$smarty->caching=false;//关闭缓存,调试中建议关闭,默认为关闭,在实际运行的时候请打开,减轻服//务器压力  
//$smarty->template_dir="templates";//设置模版目录  
//$smarty->compile_dir="compiles";//设置编译目录必选  

?>  

第二步 创建一个用于访问的php文件,通过访问这个文件,后自动生成php和html的混编文件,然后运行出来

代码: <?php  
include 'Smarty.inc.php';//使用Smarty特性  
$smarty->caching = 1;   //1和true是开启缓存,false是关闭缓存,开发调试阶段建议关闭
$smarty->cache_lifetime = 3600; //缓存的生存周期 
$smarty->cache_dir = "./caches";//设置缓存的文件目录
$smarty->assign('name','呵呵大!');//{$name}的值为“呵呵”

$arr = array(1=>'篮球',2=>'排球',3=>'足球',4=>'羽毛球');
$arr2 = array(1=>'北京',2=>'上海',3=>'河南',4=>'浙江');
$arr3 = array(1=>'男',2=>'女');
$smarty->assign('hobby', $arr);
$smarty->assign('addr', $arr2);
$smarty->assign('sex', $arr3);

$smarty->display('helloworld.html');//这个helloworld.php对应的展示页面是helloworld.html  

?>  

第三步 创建一个html文件,通过smarty的display方法传入到前面的php文件,生成混编文件

代码: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
<html xmlns="http://www.w3.org/1999/xhtml">  
<head>  
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
    <title>Helloworld</title>  
</head>  
  
<body>  
    <p>hello,{$name}</p>  </br>

{*({**}是smarty在模板html的注释)*}

{*
保存变量的使用示例

此处的get后的数据需要在地址栏里通过get传值:例:?name='zs'&action='abc'
*}
<div>get数据:{$smarty.get.name}</div>
<div>get数据:{$smarty.get.action}</div>
<hr>

{*
配置文件的使用
*}

{config_load file="demo.conf" section='info3'}

{*获取配置文件内容的形式一*}
<div>姓名:{#NAME#}</div>
<div>年龄:{#AGE#}</div>
<div>学历:{#EDU#}</div>

{*获取配置文件内容的形式二*}
<hr>
<div>姓名:{$smarty.config.NAME}</div>
<div>年龄:{$smarty.config.AGE}</div>
<div>学历:{$smarty.config.EDU}</div>

<hr>

{*数组的使用*}
<div>{$hobby['1']}<div>
<div>{$hobby['2']}<div>
<div>{$hobby['3']}<div>
<div>{$hobby['4']}<div>
{*数组遍历*}
<ul>
{foreach $hobby as  $key=>$value}
<li>{$hobby[$key]}</li>
{foreachelse}
数组为空
{/foreach}
</ul>
<hr/>
{*复选框*}
爱好:{html_checkboxes name="aihao" options=$hobby selected=2}<br>

{*下拉框*}
地址:{html_options name="dizhi" options=$addr selected=2}<br/>

{*单选框*}
性别:{html_radios name="sex" options=$sex selected=1}<br>

{*图像*}
图片:{html_image file="./images/1.jpg" border="3" height="80" width="100" alt="搜狗五笔" href="http://www.sougou.com"}


</ul>
</body>  
</html>  

这里面使用的数组和表单的内容都是结合前面的php文件写的,需要对应着写,其中有一个是关于读取配置文件的,内容为:

[info1]
NAME=张三
AGE=18
EDU=大学
[info2]
NAME=李四
AGE=30
EDU=大学
[info3]
NAME=王五
AGE=20
EDU=大学

以上这些介绍了smarty在php中的基本使用,通过使用smarty完成php文件和html文件分别开发的目的,更加适用于多人项目合作开发。

原创粉丝点击