Yii 各種url地址寫法


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

yii\helpers\Url::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');

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM