Skip to content

Instantly share code, notes, and snippets.

@LittleCoding
Created September 27, 2016 13:37
Show Gist options
  • Select an option

  • Save LittleCoding/482bbcffbaa2a1cfaa53c6bcf35273ba to your computer and use it in GitHub Desktop.

Select an option

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

chrishappy commented Feb 21, 2018

Copy link
Copy Markdown

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

@Niall-Jackson

Niall-Jackson commented Jun 18, 2020

Copy link
Copy Markdown

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

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

@hockey2112

Copy link
Copy Markdown

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
Copy Markdown

Ah, I believe I have found the solution:

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

@christinef1126

christinef1126 commented Jun 7, 2021

Copy link
Copy Markdown

Ah, I believe I have found the solution:

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

Thanks, it works perfectly.

@Alimba86

Alimba86 commented Mar 8, 2024

Copy link
Copy Markdown

Nice, thanks for sharing!

@gitressa

Copy link
Copy Markdown

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