函數定義
<?php
/**
* 掃描模板目錄,回傳含縮略圖的合法模板列表
*
* @return array ['dir' => 目錄名, 'pic' => 縮略圖相對路徑]
*/
function get_template()
{
$templates = [];
$tplRoot = CMS_ROOT . '/tpl/'; // 常數定義專案根目錄
if (!is_dir($tplRoot)) return $templates;
$dh = opendir($tplRoot);
while (($file = readdir($dh)) !== false) {
if ($file === '.' || $file === '..' || $file === '.svn') continue;
$dirPath = $tplRoot . $file;
if (is_dir($dirPath) && file_exists($dirPath . '/default.gif')) {
$templates[] = [
'dir' => $file,
'pic' => '/tpl/' . $file . '/default.gif'
];
}
}
closedir($dh);
return $templates;
}
?>
回傳結構範例
[
['dir' => 'default', 'pic' => '/tpl/default/default.gif'],
['dir' => 'blue', 'pic' => '/tpl/blue/default.gif'],
['dir' => 'mobile', 'pic' => '/tpl/mobile/default.gif']
]
前端渲染範例 (Smarty)
<?php
$tpl->assign('templates', get_template());
?>
{foreach $templates as $t}
<div class="tpl-item">
<img src="{$t.pic}" alt="{$t.dir}">
<span>{$t.dir}</span>
<button data-dir="{$t.dir}">啟用</button>
</div>
{/foreach}
擴充建議
- 支援
theme.json 讀取模板元資料(名稱、作者、版本、相容版本)
- 快取掃描結果至檔案/Redis,避免每請求掃描磁碟
- 後台提供「重新掃描」按鈕清除快取