Smarty 入門

http://tech.ddvip.com   2006年04月08日    社区交流

本文详细介绍Smarty 入門

  序言

<!-- START : Block name -->

  區域內容

  <!-- END : Block name -->

  

  這些區塊大部份都會在 PHP 程式中以 if 或 for, while 來控制它們的顯示狀態,雖然樣版看起來簡潔多了,但只要一換了顯示方式不同的樣版, PHP 程式勢必要再改一次!main.php:<?php
   include "class/Smarty.class.php";
   define('__SITE_ROOT', 'd:/appserv/web/demo'); // 最後沒有斜線
   $tpl = new Smarty();
   $tpl->template_dir = __SITE_ROOT . "/templates/";
   $tpl->compile_dir = __SITE_ROOT . "/templates_c/";
   $tpl->config_dir = __SITE_ROOT . "/configs/";
   $tpl->cache_dir = __SITE_ROOT . "/cache/";
   $tpl->left_delimiter = '<{';
   $tpl->right_delimiter = '}>';
?>

  照上面方式設定的用意在於,程式如果要移植到其他地方,只要改 __SITE_ROOT 就可以啦。 (這裡是參考 XOOPS 的 )templates/test.htm:<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=big5">
<title><{$title}></title>
</head>
<body>
<{$content}>
</body>
</html>

  現在我們要將上面的樣版顯示出來,並將網頁標題 ($title) 與內容 ($content) 更換,請將以下檔案內容命名為 test.php ,並放置在主資料夾下:test.php:<?php
   require "main.php";
   $tpl->assign("title", "測試用的網頁標題");
   $tpl->assign("content", "測試用的網頁內容");
   // 上面兩行也可以用這行代替
   // $tpl->assign(array("title" => "測試用的網頁標題", "content" => "測試用的網頁內容"));
   $tpl->display('test.htm');
?>templates_c/%%179/%%1798044067/test.htm.php:<?php /* Smarty version 2.6.0, created on 2003-12-15 22:19:45 compiled from test.htm */ ?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=big5">
<title><?php echo $this->_tpl_vars['title']; ?></title>
</head>
<body>
<?php echo $this->_tpl_vars['content']; ?>
</body>
</html>

  沒錯,這就是 Smarty 編譯過的檔案。它將我們在樣版中的變數轉換成了 PHP 的語法來執行,下次再讀取同樣的內容時, Smarty 就會直接抓取這個檔案來執行了。main.php:<?php
   include "class/Smarty.class.php";
   define( '__SITE_ROOT', 'd:/appserv/web/demo'); // 最後沒有斜線
   // 以 main.php 的位置為基準
   require_once "includes/functions.php";
   require_once "includes/include.php";
   $tpl = new Smarty();
   $tpl- >template_dir = __SITE_ROOT . "/templates/";
   $tpl- >compile_dir = __SITE_ROOT . "/templates_c/";
   $tpl- >config_dir = __SITE_ROOT . "/configs/";
   $tpl- >cache_dir = __SITE_ROOT . "/cache/";
   $tpl- >left_delimiter = '<{';
   $tpl- >right_delimiter = '}>';
?>

  modules 這個資料夾則是用來放置程式模組的,如此一來便不會把程式丟得到處都是,整體架構一目瞭然。

作者:Jace Ju    责编:豆豆技术应用

正在加载评论...