天天看点

Yii2 Url路径

Url::to

Url::to() 和 toRoute() 非常类似。这两个方法的唯一区别在于,前者要求一个路由必须用数组来指定。 如果传的参数为字符串,它将会被直接当做 URL 
Url::to() 的第一个参数可以是:

数组:将会调用 toRoute() 来生成URL。比如: ['site/index'], ['post/index', 'page' => 2] 。 详细用法请参考 toRoute() 。
带前导 @ 的字符串:它将会被当做别名, 对应的别名字符串将会返回。
空的字符串:当前请求的 URL 将会被返回;
普通的字符串:返回本身
Url::to('@web/imgs/loading2.gif') 返回的是basic/web/imgs/loading2.gif , 如果Url::to('/imgs/loading2.gif',true)则返回的是http://localhost/basic/web/imgs/loading2.gif(添加了域名,变成了绝对路径)。


// /index.php?r=site/index
echo Url::to(['site/index']);

// /index.php?r=site/index&src=ref1#name
echo Url::to(['site/index', 'src' => 'ref1', '#' => 'name']);

// /index.php?r=post/edit&id=100     assume the alias "@postEdit" is defined as "post/edit"
echo Url::to(['@postEdit', 'id' => 100]);

// the currently requested URL
echo Url::to();

// /images/logo.gif
echo Url::to('@web/images/logo.gif');

// images/logo.gif
echo Url::to('images/logo.gif');

// http://www.example.com/images/logo.gif
echo Url::to('@web/images/logo.gif', true);

// https://www.example.com/images/logo.gif
echo Url::to('@web/images/logo.gif', 'https');
           

Url::toRoute

[Url::toRoute] - 获取某一地址 => 现在测试本地路径(http://daxia.dc.weixin.com/mobile/hmConnections/user/verify-user)
1://获取某地址 - 相对路径
$url = Url::toRoute('site/index');
例如: /mobile/hmConnections/site/index

2://获取某地址 - 相对路径
$url = Url::toRoute('site/index', false);
例如: /mobile/hmConnections/site/index
说明: 等价于1 因为默认是false

3://获取某地址 - 相对路径
$url = Url::toRoute(['site/index', 'id' => 1]);
例如: /mobile/hmConnections/site/index?id=1

4://获取某地址的 - 绝对路径
$url = Url::toRoute('site/index', true);
例如: http://daxia.dc.weixin.com/mobile/hmConnections/site/index

5://获取某地址的 - 绝对路径
$url = Url::toRoute('site/index', ['id' => 1]);
例如: http://daxia.dc.weixin.com/mobile/hmConnections/site/index
说明: 参数没有输出,说明,这种写法['id' => 1], 他当成了true,所以等价于4

6://获取某地址的 - 绝对路径 (传输协议-http)
$url = Url::toRoute('site/index', 'http');
例如: https://daxia.dc.weixin.com/mobile/hmConnections/site/index
说明: 等价于4

7://获取某地址的 - 绝对路径 (传输协议-https)
$url = Url::toRoute('site/index', 'https');
例如: https://daxia.dc.weixin.com/mobile/hmConnections/site/index

           

Url::current

[Url::to] - 创建一个基于给定参数的网址 => 现在测试本地路径(http://daxia.dc.weixin.com/mobile/hmConnections/user/verify-user)

a: //获取当前路径 - 相对路径
$url = Url::current();
举例:/mobile/hmConnections/user/verify-user

b: //获取当前路径 - 相对路径
$url = Url::current(['id' => 1], false);
例如: /mobile/hmConnections/user/verify-user?id=1

c: //获取当前路径 - 绝对路径
$url = Url::current(['id' => 1], true);
例如: http://daxia.dc.weixin.com/mobile/hmConnections/user/verify-user?id=1

d: //获取当前路径 - 绝对路径 传输协议-http
$url = Url::current(['id' => 1], 'http');
例如: http://daxia.dc.weixin.com/mobile/hmConnections/user/verify-user?id=1

e: //获取当前路径 - 绝对路径 传输协议-https
$url = Url::current(['id' => 1], 'https');
例如: https://daxia.dc.weixin.com/mobile/hmConnections/user/verify-user?id=1