Yii2.0 Url助手

Url 帮助类

 use yii\helpers\Url;

获得通用 URL

有两种获取通用 URLS 的方法 :当前请求的 home URL 和 base URL 。

$relativeHomeUrl = Url::home();
$absoluteHomeUrl = Url::home(true);
$httpsAbsoluteHomeUrl = Url::home('https');
// 如果没有传任何参数,这个方法将会生成相对 URL 。
// 你可以传 true 来获得一个针对当前协议的绝对 URL;
// 或者,你可以明确的指定具体的协议类型( https , http )。

// 用法和Url::home()一样
$relativeBaseUrl = Url::base();
$absoluteBaseUrl = Url::base(true);
$httpsAbsoluteBaseUrl = Url::base('https');

创建url

Url::toRoute()

$url = Url::toRoute(['product/view', 'id' => 42]);

// generates: /index.php?r=site/index&param1=value1&param2=value2
['site/index', 'param1' => 'value1', 'param2' => 'value2']

// generates: /index.php?r=site/index&param1=value1#name
['site/index', 'param1' => 'value1', '#' => 'name']

// /index.php?r=site/index
echo Url::toRoute('site/index');

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

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

// http://www.example.com/index.php?r=site/index
echo Url::toRoute('site/index', true);

// https://www.example.com/index.php?r=site/index
echo Url::toRoute('site/index', 'https');

Url::to()

// /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::current()

从2.0.3版本开始,你可以使用 yii\helpers\Url::current() 来创建一个基于当前请求路由和 GET 参数的 URL

你可以通过传递一个 $params 给这个方法来添加或者删除 GET 参数。

// 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

// 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');

参考: -http://www.yiichina.com/doc/guide/2.0/helper-url




导航