本文共 1827 字,大约阅读时间需要 6 分钟。
Smarty 是一个高效的 PHP 模板引擎,广泛应用于动态网页生成。以下是 Smarty 配置的基础知识和实用技巧。
模板文件目录
$smarty->template_dir = "./templates";
./templates/ 目录下。编译文件目录
$smarty->compile_dir = "./templates_c";
./templates_c/ 目录。缓存文件目录
$smarty->cache_dir = "./caches";
./caches/ 目录。配置文件目录
$smarty->config_dir = "./configs";
./configs/ 目录。缓存设置
$smarty->caching = true; // 启用缓存$smarty->cache_lifetime = 60; // 缓存有效时间(秒)
$smarty = new Smarty();$smarty->caching = false; //关闭缓存(开发环境推荐)$smarty->cache_lifetime = 0; //关闭缓存(生产环境)$smarty->config_dir = "./configs";$smarty->template_dir = "./templates";$smarty->compile_dir = "./templates_c";$smarty->cache_dir = "./caches";$smarty->left_delimiter = "{";$smarty->right_delimiter = "}"; Smarty 的核心功能是通过 assign 方法赋值模板变量。
$value = "测试内容";$smarty->assign("content", $value);$smarty->display("index.html"); {$title} 欢迎访问 our site
访问时间: {$access_time}
section循环(多维数组)
{section name=loop loop=$data}{foreach $value in $data}// 内容{/foreach}{/section} foreach循环(一维数组)
{foreach item=idx from=$array}// 内容{/foreach} 条件判断
{if $a > 5}// 条件满足时显示内容{/if} 静态内容显示
{literal} {/literal} 代码格式化
{strip}// 内容{/strip} $smarty->cache_dir = "/var/www/cache";$smarty->caching = true;$smarty->cache_lifetime = 3600; // 1 小时
$smarty->display("cache.tpl", "cache_id"); $smarty->clear_all_cache();$smarty->clear_cache("tpl_file"); {insert name="cache_content"} // 内容不会被缓存 {/insert}
{block name="block_name"} // 内容不会被缓存{/block} display 方法
$smarty->display("template.tpl"); fetch 方法
$content = $smarty->fetch("template.tpl"); 缓存检查
if ($smarty->is_cached("template.tpl")) { // 内容已缓存} 通过以上配置和应用,Smarty 可以显著提升 PHP 网站的性能和开发效率。
转载地址:http://ettfk.baihongyu.com/