首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 自動掃描模板目錄:以 default.gif 縮略圖識別合法模板

     編輯:PHP 綜合知識

函數定義

<?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,避免每請求掃描磁碟
  • 後台提供「重新掃描」按鈕清除快取
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved