首页 > php框架 > smarty入门教程一

smarty入门教程一

实例1:

先来看一个简单的例子。

index.tpl

CODE:

{* 显示是smarty变量识符里的用*包含的文字为注释内容 *}
<{include file="header.tpl"}>{*页面头*}
大家好,我叫<{$name}>, 欢迎大家阅读我的smarty学习材料。
<{include file="foot.tpl"}>{*页面尾*}

上边的这个例子是一个tpl模板,其中:

1. <{**}>是模板页的注释,它在smarty对模板进行解析时不进行任何输出,仅供模板设计师对模板进行注释。

2. <{include file="xxx.tpl"}>使用此句将一个模板文件包含到当前页面中,例子中将在网站中公用事的head.tpl与foot.tpl进行了包含,你可以

这样想,使用这一句将xxx.tpl中的内容全部复制在当前语句处。当然,你不使用这一句也可以,将XXX.tpl中的内容复制到当前语句处

也是完全可以了。

3.{$name}: 模板变量,smarty中的核心组成,采用smarty定义的左边界符{与右边界符}包含着、以PHP变量形式给出,在smarty程序中将使用

$smarty->assign("name", "李晓军");将模板中的$name替换成&ldquo;李晓军&rdquo;三个字。

整个实例源程序如下:

header.tpl

CODE:

<html>
<head>
<title>大师兄smarty教程</title>
</head>
<body>


foot.tpl

CODE:

<hr>
<center> CopyRight(C) by 大师兄 2004年8月 Email: teacherli@163.com </center>
<hr>
</body>
</html>


index.tpl

CODE:

{* 显示是smarty变量识符里的用*包含的文字为注释内容 *}
{include file="header.tpl"}{*页面头*}
大家好,我叫{$name}, 欢迎大家阅读我的smarty学习材料。
{include file="foot.tpl"}{*页面尾*}

index.php


PHP:

<?php
/*********************************************
*
* 文件名: index.php
* 作 用: 显示实例程序
*
* 作 者: 大师兄
* Email: teacherli@163.com
* 修 正: forest
*********************************************/
include_once("./comm/Smarty.class.php"); //包含smarty类文件
$smarty = new Smarty(); //建立smarty实例对象$smarty
$smarty->template_dir = "./templates";//设置模板目录
$smarty->compile_dir = "./templates_c"; //设置编译目录
//----------------------------------------------------
//左右边界符,默认为{},但实际应用当中容易与JavaScript
//相冲突,所以建议设成<{}>或其它。
//----------------------------------------------------
$smarty->left_delimiter = "<{"; 
$smarty->right_delimiter = "}>";
$smarty->assign("name", "李晓军"); //进行模板变量替换
//编译并显示位于./templates下的index.tpl模板
$smarty->display("index.tpl"); 
?>

最终执行这个程序时将显示为:

================================

执行index.php

================================

<html>
<head>
<title>大师兄smarty教程</title>
</head>
<body>
大家好,我叫李晓军, 欢迎大家阅读我的smarty学习材料。
<hr>
<center> CopyRight(C) by 大师兄 2004年8月<center>
<hr>
</body>
</html>


教程地址:http://www.phprm.com/frame/863412636129362b8dc7a4e3fabac1f6.html

欢迎转载!但请带上文章地址^^

标签:none

发表留言