Skip to content

Instantly share code, notes, and snippets.

@LittleCoding
Created September 27, 2016 13:37
Show Gist options
  • Save LittleCoding/482bbcffbaa2a1cfaa53c6bcf35273ba to your computer and use it in GitHub Desktop.
Save LittleCoding/482bbcffbaa2a1cfaa53c6bcf35273ba to your computer and use it in GitHub Desktop.
Current URL path via Twig in Drupal 8
{#
/**
* @file
* Get the current URL path via Drupal 8 route name and twig function.
*/
#}
<a href="{{ url('<current>') }}">Current page</a>
@chrishappy
Copy link

chrishappy commented Feb 21, 2018

If you use this in a block view, remember to turn off block caching in the "Advanced Settings"

@Niall-Jackson
Copy link

Niall-Jackson commented Jun 18, 2020

Note that this returns the complete URL, not the path. If you just want the path, use

{{ path('<current>') }}

@hockey2112
Copy link

This works great, but what if I only need a specific parameter from the URL? For example, I want to style a portion of the Commerce checkout process if the user is on the Review page (mysite.com/checkout/388/review). How can I get just that final parameter (review)? When I use this code (

) in the file "commerce-checkout-form--with-sidebar.html.twig", I get the following output:

If I can get just "review" as that part of the class, I will be able to use CSS to style that area of the order review page.

@hockey2112
Copy link

Ah, I believe I have found the solution:

{% set url = url('')['#markup'] %}{{ url|split('/')|last }}

@christinef1126
Copy link

christinef1126 commented Jun 7, 2021

Ah, I believe I have found the solution:

{% set url = url('')['#markup'] %}{{ url|split('/')|last }}

Thanks, it works perfectly.

@Alimba86
Copy link

Alimba86 commented Mar 8, 2024

Nice, thanks for sharing!

@gitressa
Copy link

Thanks, works well! For more URL path Twig tips in Drupal, see Functions in Twig templates.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment