---
title: "php smarty基本使用"
author: "bask"
date: "2009-10-21T20:56:12Z"
tags: []
categories: ["编程语言"]
slug: "php-smarty"
draft: false
lastmod: "2009-12-08T19:36:21Z"
id: 499305
url: "https://bask.iteye.com/blog/499305"
---

1.基本类

```php

//smarty_config.php
<?php
define('TEMPLATE_DIR','templates/');
define('COMPILE_DIR','templates_c/');
define('CONFIG_DIR','configs/');
define('CACHE_DIR','cache/');

?>
//View.class.php
<?php
//配置文件
require_once 'configs/smart_config.php';
//Smarty类
require('smarty/Smarty.class.php');
class View extends Smarty {
	function SmartyFactory() {
		$this->Smarty();
		//模板路径
		$this->template_dir = TEMPLATE_DIR;
		//编译后文件
		$this->compile_dir = COMPILE_DIR;
		//配置文件
		$this->config_dir = CONFIG_DIR;
		//缓存文件
		$this->cache_dir = CACHE_DIR;
		$this->debugging = true;
	}
	//重新封装display 个人习惯改成show
	function show($name,$cacheId='') {
		if($cacheId == '') 
			$this->display($name.'.htm');
		else 
			$this->display($name.'.htm',$cacheId);
	}
	//重新封装assign 习惯用add
	function add($name,$value) {
		$this->assign($name,$value);
	}
}
?>
```

<span style="color:red">
基本目录如:
test
    |-configs
    |-templates
    |-templates_c
    |-cache
    |-smarty --smarty lib</span>
2.基本使用

```php

//index.php
<?php
require_once('View.php');
//数据查询 mysql_fetch_assoc() 返回数组
//数据库层封装
//如:$User = new User();
//$Users = $User->paging('参数');
$View = new View();
$View->add("users",$Users);
$View->show("index");
?>
```

<span style="color:red">//public.conf

public = public/
img = public/img/
css = public/css/
js = public/js/</span>

```html

//index.htm --在templates文件夹下 简短介绍下
<html>
<!-- 包含meta.htm文件-->
{include file="meta.htm"}
<!-- 利用smarty config文件 定义基本信息-->
{config_load file=public.conf section="public"}
<!-- 略 -->
<table>
	<tr>
		<!-- {#img#} img的基本路径 对于一般小网站的做法 如有是使用了二级域名的静态服务器没必要了-->
		<td><input type="image" src="{#img#}xxx.gif"/></td>
	</tr>
</table>
<table>
<tr>
	<td>id</td><td>用户名</td>
</tr>
<!-- 循环遍历 数组里的数据 -->
<!-- loop=$Users 在php中的变量 name=user循环的名称-->
{section name=user loop=$Users}
	<tr>
		<td>{$Users[user].id}</td>
		<td>{$Users[user].username}</td>
	</tr>
{/section}
</table>
<!-- 包含另一个php 这个php可以是index.php这样的模板输出-->
{php}
	include("other.php");
{/php}
</html>
```