温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何正确的使用smarty模板

发布时间:2021-03-23 16:45:28 来源:亿速云 阅读:138 作者:Leah 栏目:开发技术

本篇文章为大家展示了如何正确的使用smarty模板,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

首先, 在官网下载smarty3模板文件,然后解压。

在解压之后的文件夹中,libs是smarty模板的核心文件,demo里面有示例程序。

我们把libs文件夹复制到我们的工作目录,然后重命名为smarty。

如何正确的使用smarty模板

假设我们在controller目录下的index.php中使用smarty模板。

index.php

<?php
require '../smarty/Smarty.class.php';
$smarty = new Smarty;
$smarty->debugging = false;  //开启debug模式
$smarty->caching = true;  //开启缓存
$smarty->cache_lifetime = 120; //缓存时间
$smarty->left_delimiter = '<{';  //左定界符
$smarty->right_delimiter = '}>';  //右定界符
$smarty->template_dir = __DIR__.'/../view/';  //视图目录
$smarty->compile_dir = __DIR__ . '/../smarty/compile/';  //编译目录
$smarty->config_dir = __DIR__ . '/../smarty/configs/'; //配置目录
$smarty->cache_dir = __DIR__ . '/../smarty/cache/';  //缓存目录
$list = range('A', 'D');
$smarty->assign("list", $list);
$smarty->assign("name", "zhezhao");
$smarty->display('index.html');

模板文件index.html

<html>
<head>
  <title></title>
</head>
<body>
  <p><h2><{$name}></h2></p>
  <{foreach $list as $k=>$v }>
    <p><h2><{$k}> : <{$v}></h2></p>
  <{/foreach}>
</body>
</html>

上述方法的优点是使用起来配置比较简单,缺点也是显而易见的,我们controller目录下可能有很多页面调用smarty模板,在每个页面都需要将上述方法配置一遍。

解决方法有两种:

将smarty模板的配置信息写到一个文件中,然后其他页面可以通过包含该文件使用smarty对象。

require '../smarty/Smarty.class.php';
$smarty = new Smarty;
$smarty->debugging = false;  //开启debug模式
$smarty->caching = true;  //开启缓存
$smarty->cache_lifetime = 120; //缓存时间
$smarty->left_delimiter = '<{';  //左定界符
$smarty->right_delimiter = '}>';  //右定界符
$smarty->template_dir = __DIR__.'/../view/';  //视图目录
$smarty->compile_dir = __DIR__ . '/../smarty/compile/';  //编译目录
$smarty->config_dir = __DIR__ . '/../smarty/configs/'; //配置目录
$smarty->cache_dir = __DIR__ . '/../smarty/cache/';  //缓存目录

我们自己编写一个类,继承自Smarty类,然后将配置信息写在构造函数中。

我们编写mySmarty类

<?php
require '../smarty/Smarty.class.php';
class mySmarty extends Smarty{
  public function __construct(array $options = array()){
    parent::__construct($options);
    $this->debugging = false; //开启debug模式
    $this->caching = true; //开启缓存
    $this->cache_lifetime = 120;  //缓存时间
    $this->left_delimiter = '<{'; //左定界符
    $this->right_delimiter = '}>'; //右定界符
    $this->setTemplateDir(__DIR__.'/../view/');  //视图目录
    $this->setCompileDir(__DIR__ . '/../smarty/compile/'); //编译目录
    $this->setConfigDir(__DIR__ . '/../smarty/configs/'); //配置目录
    $this->setCacheDir(__DIR__ . '/../smarty/cache/'); //缓存目录
  }
}

此时,controller里面的index.php代码可优化为:

<?php
require 'mySmarty.php';
$smarty = new mySmarty;
$list = range('A', 'D');
$smarty->assign("list", $list);
$smarty->assign("name", "zhezhao");
$smarty->display('index.html');

上述内容就是如何正确的使用smarty模板,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI