echo Url::home();

生成入口地址/yii2test/frontend/web/index.php;

echo  Url::base();
生成入口文件夹地址:/yii2test/frontend/web

echo  Url::base(true);

生成带有域名的入口文件夹地址:http://localhost/yii2test/frontend/web

echo Url::to();

生成当前浏览器文档地址(同时携带参数)/yii2test/frontend/web/index.php?r=item%2Fview&id=4

Url::toRoute($route, $scheme = false); $route必须为数组格式;

echo Url::toRoute(['item/view']);

生成item为控制器,view为action,地址为:/yii2test/frontend/web/index.php?r=item%2Fview

还有其它例子:echo Url::toRoute(['site/index', 'src' => 'ref1', '#' => 'name']);

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

Url::to() 的第一个参数可以是:

  • 数组:将会调用 toRoute() 来生成URL。比如: ['site/index']['post/index', 'page' => 2] 。 详细用法请参考 toRoute() 。
  • 带前导 @ 的字符串:它将会被当做别名, 对应的别名字符串将会返回。
  • 空的字符串:当前请求的 URL 将会被返回;
  • 普通的字符串:返回本身

 以下是一些使用示例:

复制代码
// /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');
复制代码

yiihelpersUrl::current() 来创建一个基于当前请求路由和 GET 参数的 URL

复制代码
// assume $_GET = ['id' => 123, 'src' => 'google'], current route is "post/view"

// /index.php?r=post/view&id=123&src=google
echo Url::current();

// /index.php?r=post/view&id=123
echo Url::current(['src' => null]);
// /index.php?r=post/view&id=100&src=google
echo Url::current(['id' => 100]);
复制代码

记住 URLs

有时,你需要记住一个 URL 并在后续的请求处理中使用它。 你可以用以下方式达到这个目的:

复制代码
// Remember current URL 
Url::remember();

// Remember URL specified. See Url::to() for argument format.
Url::remember(['product/view', 'id' => 42]);

// Remember URL specified with a name given
Url::remember(['product/view', 'id' => 42], 'product');
复制代码

在后续的请求处理中,可以用如下方式获得记住的 URL:

$url = Url::previous();
$productUrl = Url::previous('product');

检查相对 URLs

你可以用如下代码检测一个 URL 是否是相对的(比如,包含主机信息部分)。

$isRelative = Url::isRelative('test/it');