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

Buttons Kavanagh

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 %}

Last updated by on .

What Are Your Thoughts?

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