webman 视图模版里支持tp/thinkphp方式的自己封装url 路由(注意,需要先composer安装tp视图插件)

weidu
//用法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拼接,也可带数组参数或字符串参数
if (!function_exists('url')) {
    function url($path, $params = []) {
        if(is_string($params)){
            //转成数组,重写$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);
                    //如果参数存在匹配变量,替换并移除(?后的key)
                    unset($params[$key]);
                }
            }
        }
        //还剩有参数,做拼接
        if(!empty($params)){
            $url .= strstr($url,'?') ? '&'.http_build_query($params) : '?'.http_build_query($params);
        }
        return $url;
    }
}
102 0 1
0个评论

weidu

200
积分
0
获赞数
0
粉丝数
16天前 加入
×
🔝