toRoute() public static method
Creates a URL for the given route.
This method will use yii\web\UrlManager to create a URL.
You may specify the route as a string, e.g., site/index
. You may also use an array if you want to specify additional query parameters for the URL being created. The array format must be:
// generates: /index.php?r=site/index¶m1=value1¶m2=value2 ['site/index', 'param1' => 'value1', 'param2' => 'value2']
If you want to create a URL with an anchor, you can use the array format with a #
parameter. For example,
// generates: /index.php?r=site/index¶m1=value1#name ['site/index', 'param1' => 'value1', '#' => 'name']
A route may be either absolute or relative. An absolute route has a leading slash (e.g. /site/index
), while a relative route has none (e.g. site/index
or index
). A relative route will be converted into an absolute one by the following rules:
- If the route is an empty string, the current route will be used;
- If the route contains no slashes at all (e.g.
index
), it is considered to be an action ID of the current controller and will be prepended with yii\web\Controller::$uniqueId; - If the route has no leading slash (e.g.
site/index
), it is considered to be a route relative to the current module and will be prepended with the module's uniqueId.
Starting from version 2.0.2, a route can also be specified as an alias. In this case, the alias will be converted into the actual route first before conducting the above transformation steps.
Below are some examples of using this method:
// /index.php?r=site%2Findex echo Url::toRoute('site/index'); // /index.php?r=site%2Findex&src=ref1#name echo Url::toRoute(['site/index', 'src' => 'ref1', '#' => 'name']); // http://www.example.com/index.php?r=site%2Findex echo Url::toRoute('site/index', true); // https://www.example.com/index.php?r=site%2Findex echo Url::toRoute('site/index', 'https'); // /index.php?r=post%2Findex assume the alias "@posts" is defined as "post/index" echo Url::toRoute('@posts');
public static string toRoute ( $route, $scheme = false ) | ||
---|---|---|
$route | string|array |
Use a string to represent a route (e.g. |
$scheme | boolean|string |
The URI scheme to use in the generated URL:
|
return | string |
The generated URL |
throws | yii\base\InvalidParamException |
a relative route is given while there is no active controller |
Please login to continue.