在 ThinkPHP 模板開發中,正確使用內建路徑常量是實現資源引用靈活、專案遷移無憂的關鍵。本文系統梳理 9 大核心常量的含義、輸出示例及模板替換機制。
www.test.com/other/FormIndexindexhttps://www.test.com/other/Form/index.php/Index/index| 常量 | 輸出示例 | 用途說明 |
|---|---|---|
| __ROOT__ | /other/thinkphp/mydemo | 網站根目錄(相對域名) |
| __SELF__ | /other/thinkphp/mydemo/Form/index.php | 當前頁面完整 URL(含入口文件) |
| __ACTION__ | /other/thinkphp/mydemo/Form/index.php/Index/index | 當前操作完整 URL |
| __URL__ | /other/thinkphp/mydemo/Form/index.php/Index | 當前模組地址 |
| __APP__ | /other/thinkphp/mydemo/Form/index.php | 當前項目入口地址 |
| __PUBLIC__ | /other/thinkphp/mydemo/Public | 網站公共資源目錄(CSS/JS/圖片) |
| ../public | /other/thinkphp/mydemo/Form/Tpl/default/Public | 模板主題公共目錄(不區分大小寫) |
| APP_PUBLIC_URL | /other/thinkphp/mydemo/Form/Tpl/default/Public | 項目公共模板資源目錄 |
| WEB_PUBLIC_URL | /other/thinkphp/mydemo/Public | 網站級公共資源目錄(同 __PUBLIC__) |
ThinkPHP 在模板編譯時,會自動將常量標籤替換為對應的 PHP 常量值,核心邏輯如下:
// 項目公共目錄
$tmplContent = str_ireplace('../public', APP_PUBLIC_URL, $tmplContent);
// 網站公共目錄
$tmplContent = str_replace('__PUBLIC__', WEB_PUBLIC_URL, $tmplContent);
// 網站根目錄
$tmplContent = str_replace('__ROOT__', __ROOT__, $tmplContent);
// 當前項目地址
$tmplContent = str_replace('__APP__', __APP__, $tmplContent);
// 當前模組地址
$tmplContent = str_replace('__URL__', __URL__, $tmplContent);
// 當前操作地址
$tmplContent = str_replace('__ACTION__', __ACTION__, $tmplContent);
// 當前頁面地址
$tmplContent = str_replace('__SELF__', __SELF__, $tmplContent);
__PUBLIC__ 或 __ROOT__,避免硬編碼絕對路徑。__ACTION__、__URL__、U() 函數動態生成 URL。../public(模板相對路徑)。__PUBLIC__(網站級)與 APP_PUBLIC_URL(項目級/主題級)。var ROOT = '__ROOT__'; 供 JS 使用。__SELF__ 包含查詢字串的特性,表單 action="__SELF__" 可保持當前參數不丟失。熟練掌握這套路徑體系,能讓 ThinkPHP 專案在開發、測試、生產環境間無縫遷移,極大降低維護成本。