webman 視圖模版里支持tp/thinkphp方式的自己封裝url 路由(注意,需要先composer安裝tp視圖插件)
//用法1 href="{:url('/admin/category/edit/:id?cc=33',['id'=>1,'c'=>2])}"
//用法2 href="{:url('/admin/category/edit/:id?cc=33',"id=1&c=2")}"
//說明*:本方法支持 路由變量:name 替換,也可?cc=xxx拼接,也可帶數(shù)組參數(shù)或字符串參數(shù)
if (!function_exists('url')) {
function url($path, $params = []) {
if(is_string($params)){
//轉成數(shù)組,重寫$params
parse_str($params, $outputArray);
$params = $outputArray;
}
$req = request();
$listen = config('process.webman.listen');
$ssl = strstr($listen,'http:') ? 'http' : 'https';
$url = $ssl."://".$req->host().'/'.trim($path,'/');
//判斷path里面,有沒有變量:key
preg_match_all('/\:([^\/\?]+)/',$path,$preg);
if(isset($preg[1]) && !empty($preg[1])){
foreach ($params as $key => $value){
if(in_array($key,$preg[1])){
$url = str_replace(':'.$key,$value,$url);
//如果參數(shù)存在匹配變量,替換并移除(?后的key)
unset($params[$key]);
}
}
}
//還剩有參數(shù),做拼接
if(!empty($params)){
$url .= strstr($url,'?') ? '&'.http_build_query($params) : '?'.http_build_query($params);
}
return $url;
}
}
個評論