How do I get a page’s current URL in Twig for Drupal 8?

November 20, 2017

Having access to a site’s URL in your templates can come in handy for many different use cases, but one of the more common scenarios might be for those of you building multi-sites.

Let’s say you’re building a site with various domain names and you want to be able to conditionally change some content or functionality for each domain in your Twig templates. You can get the current URL and parse it for a substring like this:

{% set site_url = url("<current>") %}
{% if 'example-one.com' in site_url|render|render %}
     {# example-one.com content #}
{% elseif 'example-two.com' in site_url|render|render %}
     {# example-two.com content #}
{% endif %}

Stay in Touch!

Subscribe to our newsletter.

Solutions Architecture

browse through our blog articles

Blog Archive