.. php:namespace:: Cake\View\Helper
.. php:class:: UrlHelper(View $view, array $config = [])
The UrlHelper makes it easy for you to generate URL's from your other helpers. It also gives you a single place to customize how URLs are generated by overriding the core helper with an application one. See the :ref:`aliasing-helpers` section for how to do this.
.. php:method:: build(mixed $url = null, boolean|array $full = false)
Returns a URL pointing to a combination of controller and action.
If $url
is empty, it returns the REQUEST_URI
, otherwise it
generates the URL for the controller and action combo. If full
is
true
, the full base URL will be prepended to the result:
echo $this->Url->build([ "controller" => "Posts", "action" => "view", "bar", ]); // Output /posts/view/bar
Here are a few more usage examples:
URL with extension:
echo $this->Url->build([ "controller" => "Posts", "action" => "list", "_ext" => "rss", ]); // Output /posts/list.rss
URL (starting with '/') with the full base URL prepended:
echo $this->Url->build('/posts', true); // Output http://somedomain.com/posts
URL with GET parameters and fragment anchor:
echo $this->Url->build([ "controller" => "Posts", "action" => "search", "?" => ["foo" => "bar"], "#" => "first", ]); // Output /posts/search?foo=bar#first
The above example uses the ?
key which is useful when you want to be
explicit about the query string parameters you are using, or if you want a query
string parameter that shares a name with one of your route placeholders.
URL for named route:
echo $this->Url->build(['_name' => 'product-page', 'slug' => 'i-m-slug']); // Assuming route is setup like: // $router->connect( // '/products/:slug', // [ // 'controller' => 'Products', // 'action' => 'view', // ], // [ // '_name' => 'product-page', // ] // ); /products/i-m-slug
The 2nd parameter allows you to define options controlling HTML escaping, and whether or not the base path should be added:
$this->Url->build('/posts', [ 'escape' => false, 'fullBase' => true, ]);
URL with asset timestamp wrapped by a <link rel="preload"/>
, here pre-loading
a font. Note: The file must exist and Configure::read('Asset.timestamp')
must return true
or 'force'
for the timestamp to be appended:
echo $this->Html->meta([ 'rel' => 'preload', 'href' => $this->Url->assetUrl( '/assets/fonts/yout-font-pack/your-font-name.woff2' ), 'as' => 'font', ]);
.. versionadded:: 3.3.5 ``build()`` accepts an array as the 2nd argument as of 3.3.5
If you are generating URLs for CSS, Javascript or image files there are helper methods for each of these asset types:
// Outputs /img/icon.png $this->Url->image('icon.png'); // Outputs /js/app.js $this->Url->script('app.js'); // Outputs /css/app.css $this->Url->css('app.css');
.. versionadded:: 3.2.4 The asset helper methods were added in 3.2.4.
For further information check Router::url in the API.