4-2
根據不同動作自動載入相對應樣板
一、先替各個動作準備好前端界面
- 我們目前有三個動作:
- 「
index.php」沒有 op 時,主內容區顯示「所有文章」界面,亦即 main.tpl,這個不用處理
- 「
index.php?op=embed」主內容區顯示「產生內嵌語法」界面 embed.tpl,做個空的 templates/embed.tpl,內容之後再做
- 「
admin.php」沒有 op 時,管理頁面的主內容區顯示「發布新聞」界面 create.tpl
二、根據變數自動載入
- 修改
index.php 及 admin.php 用 $smarty->assign('now_op', $op); 將目前的動作送至樣板
- 順便替
index.php 的 switch 預設值設定一個 $op 值為 main(這樣才能載入 main.tpl)
<?php
require 'function.php';
require 'vendor/autoload.php';
use Smarty\Smarty;
$smarty = new Smarty();
// 過濾外部傳來變數
$op = filter_input_var('op');
switch ($op) {
case 'embed':
# code...
break;
default:
$op = "main";
break;
}
$smarty->assign('now_op', $op);
$smarty->display('index.tpl');
admin.php 的 switch 預設值也設定一個 $op 值為 create(這樣才能載入 create.tpl)
<?php
require 'function.php';
require 'vendor/autoload.php';
use Smarty\Smarty;
$smarty = new Smarty();
// 過濾外部傳來變數
$op = filter_input_var('op');
switch ($op) {
default:
$op = "create";
break;
}
$smarty->assign('now_op', $op);
$smarty->display('index.tpl');
- 最後最關鍵處,請修改
index.tpl 及 admin.tpl ,主內容區可以根據 $now_op 的值來自動 include 不同的樣板檔(樣板中的變數要用``隔開)
<main class="col-md-9">
{include file="`$now_op`.tpl"}
</main>