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

Pat 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 '' in site_url|render|render %}
     {# content #}
{% elseif '' in site_url|render|render %}
     {# content #}
{% endif %}

Last updated by on .

What Are Your Thoughts?

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