0

URL in yii2

In this article i will show you “how to use some class(Html & Url) in yii2” to get relative and absolute URL.

*note :
My url yii2 located in http://localhost/yii2_advanced/
directory in /var/ww/html/yii2_advanced

index.php (located in frontend/views/test_url/)

<?php 
use yii\helpers\Html; 
use yii\helpers\Url;
 
/** 
* A HREF 
*/ 

// <a href='site/index'>Text</a>
echo Html::a('Text', 'site/index');

// <a href='/yii2_advanced/frontend/web/index.php?r=controller/action'>E</a>
echo Html::a('E', ['/controller/action']); 



/** 
* URL 
*/ 

// /yii2_advanced/frontend/web 
echo Yii::getAlias('@web'); 

// /var/www/html/yii2_advanced/frontend 
echo Yii::getAlias('@app'); 

// /var/www/html/yii2_advanced/frontend/runtime 
echo Yii::getAlias('@runtime'); 

// /var/www/html/yii2_advanced/vendor 
echo Yii::getAlias('@vendor'); 

// /var/www/html/yii2_advanced/vendor/npm 
echo Yii::getAlias('@npm'); 

// /var/www/html/yii2_advanced/vendor/bower 
echo Yii::getAlias('@bower'); 

// /var/www/html/yii2_advanced/vendor/yiisoft/yii2 
echo Yii::getAlias('@yii'); 

// /yii2_advanced/frontend/web/index.php?r=test_url/index 
echo Url::current(); 

// /yii2_advanced/frontend/web 
echo Url::base(); 

// http://localhost/yii2_advanced/frontend/web 
echo Url::base(true); 

// /yii2_advanced/frontend/web 
echo Url::base(false); 

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

// current url 
// yii2_advanced/frontend/web/index.php?r=test_url/index 
echo  Url::to(); 

// images/photo.jpg 
echo Url::to('images/photo.jpg'); 

// http://localhost/yii2_advanced/frontend/web/images/photo.jpg 
echo Url::to('@web/images/photo.jpg', true); 

// /yii2_advanced/frontend/web/images/photo.jpg 
echo Url::to('@web/images/photo.jpg', false); 

// /yii2_advanced/frontend/web/index.php?r=site/index&id=2#name 
echo Url::to(['site/index', 'id' => '2', '#' => 'name']);

// /yii2_advanced/frontend/web/index.php?r=book
Yii::setAlias('@Yourcontroller', '/book');
echo Url::to(['@Yourcontroller']);
?>

reference :
http://www.yiiframework.com/doc-2.0/guide-concept-aliases.html
http://www.yiiframework.com/doc-2.0/yii-helpers-baseurl.html

[related_post themes="text" id="951"]

Ambar Hasbiyatmoko

Hello, I’m web developer. Passionate about programming, networking and web server. @kaskus  @facebook

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.