实现判断 首页 列表页 搜索页 内容页等 比如 如 某个css想只在首页显示 或者内容页 列表页 就可进行判断
在 app/common.php 最后 加
/**
* 判断是否为首页
* @return bool
*/
if (!function_exists('is_index')) {
function is_index()
{
// 修复:使用think\facade\Request(TP6正确的Request调用方式)
$request = \think\facade\Request::instance();
$controller = strtolower($request->controller());
$action = strtolower($request->action());
// 匹配首页常见的控制器/方法组合
return ($controller === 'index' && $action === 'index')
|| ($controller === 'home' && $action === 'index')
|| ($request->pathinfo() === '' || $request->pathinfo() === '/');
}
}
/**
* 判断是否为列表页
* @return bool
*/
if (!function_exists('is_list')) {
function is_list()
{
$request = \think\facade\Request::instance();
$action = strtolower($request->action());
$path = $request->pathinfo();
// 匹配列表页特征:action包含list、category,或URL包含分类ID参数
return str_contains($action, 'list')
|| str_contains($action, 'category')
|| $request->has('cid')
|| $request->has('catid')
|| str_contains($path, '/category/')
|| str_contains($path, '/list/');
}
}
/**
* 判断是否为详情页
* @return bool
*/
if (!function_exists('is_show')) {
function is_show()
{
$request = \think\facade\Request::instance();
$action = strtolower($request->action());
$path = $request->pathinfo();
// 匹配详情页特征:action包含show、detail,或URL包含文章ID参数
return str_contains($action, 'show')
|| str_contains($action, 'detail')
|| $request->has('id')
|| $request->has('aid')
|| str_contains($path, '/show/')
|| str_contains($path, '/detail/');
}
}
/**
* 判断是否为搜索页
* @return bool
*/
if (!function_exists('is_search')) {
function is_search()
{
$request = \think\facade\Request::instance();
$controller = strtolower($request->controller());
$action = strtolower($request->action());
// 匹配搜索页特征
return $controller === 'search'
|| $action === 'search'
|| $request->has('keyword')
|| str_contains($request->pathinfo(), '/search/');
}
}
/**
* 判断是否为404页面
* @return bool
*/
if (!function_exists('is_404')) {
function is_404()
{
$request = \think\facade\Request::instance();
// 检测响应状态码或404相关特征
return $request->server('REDIRECT_STATUS') == 404
|| str_contains(strtolower($request->pathinfo()), '404')
|| $request->controller() === 'Error' && $request->action() === 'index';
}
}
/**
* 获取当前页面类型
* @return string 页面类型标识:index/list/show/search/404/other
*/
if (!function_exists('get_page_type')) {
function get_page_type()
{
if (is_index()) return 'index';
if (is_list()) return 'list';
if (is_show()) return 'show';
if (is_search()) return 'search';
if (is_404()) return '404';
return 'other';
}
}
判断标签 全局
<!-- 1. 首页判断 -->
{if(is_index())}
这是首页
{else}
不是首页
{/if}
<!-- 2. 列表页判断 -->
{if(is_list())}
这是列表页
{else}
不是列表页
{/if}
<!-- 3. 详情页判断 -->
{if(is_show())}
这是详情页
{else}
不是详情页
{/if}
<!-- 4. 搜索页判断 -->
{if(is_search())}
这是搜索页
{else}
不是搜索页
{/if}
<!-- 5. 404页面判断 -->
{if(is_404())}
这是404页面
{else}
不是404页面
{/if}


发表评论 取消回复