程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> 關於PHP編程 >> Smarty快速入門之二

Smarty快速入門之二

編輯:關於PHP編程

為了以後更方便的使用smarty,我們可以將“加載Smarty 模版引擎”、“建立 Smarty 對象”、“設定Smarty 對象的參數”這三步放到一個公共的php文件內,以後在需要使用的地方我們直接reuqire一下,即可,例如:

1. 建立一個main.php

<?php
include smarty/Smarty.class.php;
//下次程序移植時只需要修改ROOT指向位置即可~
const DIR_SEP = DIRECTORY_SEPARATOR;
define(ROOT, D:.DIR_SEP._PHP_Test.DIR_SEP.Test2.DIR_SEP); $tpl = new Smarty();
$tpl->template_dir = ROOT.templates.DIR_SEP;
$tpl->complie_dir = ROOT.templates_c.DIR_SEP;
$tpl->config_dir = ROOT.configs.DIR_SEP;
$tpl->cache_dir  = ROOT.cache.DIR_SEP;
$tpl->left_delimiter = <{;
$tpl->right_delimiter = }>;
?> 

注1:此處為何要使用DIRECTORY_SEPARATOR?(點擊查看)

注2:left_delimiter和right_delimiter為左右結束符變量,此處可定義為其他字符串(默認為{})。

2. 在templates下,新建立一個test.htm

 <html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title><{$title}></title>
</head>
<body>
 <{$content}>
</body>
</html>

3. 調用模板頁給title和content填充內容,新建一個test_smarty_1.php

<?php
require main.php;
$tpl->assign(title, New Message);
$tpl->assign(content, This is test smarty!);
$tpl->display(test.htm);
?>

也可以這樣寫

<?php
require main.php;
$tpl->assign(array(title=>NewMessage, content=>This is test smarty!));
$tpl->display(test.htm);
?>

輸出結果:

頁面title顯示:NewMessage

頁面內容顯示:This is test smarty!

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved