Learn how to retrieve the host url, actual canonical route with twig.

With twig you can generate a url using the path tag, however this function only generates a relative path to your resources.

{# Outputs: 
  But wheres my domain :( ?

But sometimes, a relative path is not only what we need (although is functional for redirect to another path), for example to optimize SEO you are likely to handle canonical urls.

Server and routes with canonical url

To retrieve the canonical path of your domain (including protocol) use:


Then, if you need for example the canonical path of a resource (an image), then you'll use :

<img src="{{app.request.getSchemeAndHttpHost()}}{{asset('path-to/image.png')}}" />

{# or #}

{% set domain = app.request.getSchemeAndHttpHost() %}
{% set filepath = asset('path-to/image.png')%}

<img src="{{domain ~ filepath}}" />

{# that should ouput something like #}

<img src="http://ourcodeworld.com/path-to/image.png" />

And if you need to retrieve the canonical url of a route, then use :

{% set domain = app.request.getSchemeAndHttpHost() %}
{% set route = path('myroute_identifier')%}

<a href="{{domain ~ route}}">Go to my route</a>

Actual url

To generate the actual url with twig use :

{{ url(app.request.attributes.get("_route"), app.request.attributes.get("_route_params")) }}

For example, to optimize seo you should include

<meta property="og:url" content="{{ url(app.request.attributes.get("_route"), app.request.attributes.get("_route_params")) }}"/>

{#For example for the actual article, the path should be #}

<meta property="og:url" content="http://ourcodeworld.com/articles/read/105/how-to-get-the-canonical-url-of-a-path-actual-route-and-host-domain-with-twig"/>

Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.