Smarty模板引擎快速入门

开始写smarty的学习笔记,打算一共用大概15到20小时完成对smarty的学习并立即开始使用。没兴趣先开始看繁琐枯燥的手册,直接学写个简单流程就能掌握很多东西。

首先下载smarty然后复制 lib 文件夹到网站目录里,这里我复制到根目录了。
然后需要另外建立4个文件夹,分别是cache/,templates/,templates_c/, config/。这四个文件夹我通通建立在templates文件夹里,与lib并行。

之后在4个文件夹的templates里建立一个index.tpl文件。写入:

[php]<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>test</title>
</head>
<body>
{$hello}
</body>
</html>[/php]

根目录新建index.php

[php]
<?php
//调用Smarty类文件
require 'libs/Smarty.class.php';
//实例化Smarty
$smarty = new Smarty;

//制定4个目录的位置
$smarty->template_dir = "templates/templates";
$smarty->compile_dir = "templates/templates_c";
$smarty->config_dir = "templates/config";
$smarty->cache_dir = "templates/cache";

//缓存是否开启
$smarty->caching = true;

//参数赋值
$hello = "Hello World!";
//传递赋值
$smarty->assign("hello",$hello);

//引用模板文件
$smarty->display('index.tpl');

?>[/php]

输出如下:

[php]
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>test</title>
</head>
<body>
Hello World!
</body>
</html>[/php]

详解一下:

1.四个目录分别是cache_dir 高速缓存目录,template_dir模板文件目录,compile_dir存储编译后的模板, config_dir配置目录
2.模板代码是{}开头与结束的,值与php一样需要加$,数组用法:
Hello,{$exp.name}! Good {$exp.time},
编译:
$hello[name] = “Mr. Green”;
$hello[time]=”morning”;
$smarty->assign(“exp”,$hello);
模板注释方法:{* Smarty *}
3.模板调用模板:{include file="header.tpl"}

添加新评论