5

I need the argument value in the theme templates and using the views-views-fields--view_name--block_1.jhtml.twig.


I'm current getting the current URL like that:

{% set url = url('current')%}

Which outputs:

https://example.com/questions/12225

But I need only the 12225 value from the current url. How can I get the last parameter from the current URL in Twig?

7

You could use Twig's split filter, though I don't recommend scripting too much inside templates.

Instead I recommend to pass the value over to Twig from a preprocess function from inside your theme or a custom module via template_preprocess_views_view_fields.

/**
 * Implements template_preprocess_views_view_fields().
 */
function MYTHEME/MYMODULE_preprocess_views_view_fields(&$variables) {

  // Retrieve an array which contains the path pieces.
  $current_path = \Drupal::service('path.current')->getPath();

  if ($current_path[0] == 'questions') {
    $variables['question_id'] = $current_path[1];
  }
}

And then inside your template print it for example like so:

{% if question_id %}
  <div id="{{ question_id }}">Question ID: {{ question_id }}</div>
{% endif %}
5

I don't know it is best way or not but can help you You are using the {% set url = url('current>') %} After dump, it turned out that's what

array(3) { 
         ["#markup"]=>
                 string(23) "http://example.com/category" ["#cache"]=> array(3) { 
      ["contexts"]=> array(2) { [0]=> string(5) "route" [1]=>string(8) 
            "url.site" } ["tags"]=> array(0) { } ["max-age"]=> int(-1) } 
        ["#attached"]=> array(0) { } }

Convert array to sting

{% set url = url('current>')['#markup'] %}

{{ url|split('/')|last }}

you will get the last value from theurl

  • Is this a typo 'current>' the trailing angle bracket? – leymannx Sep 21 '18 at 6:52
  • <current> showing as blank in the comment so i have to type this but its value will not changes after url change , aftrer cache flush its value change – Manmeet Khurana Sep 21 '18 at 6:55
-1

To fetch the current path with query string in views you can also use the Views Current Path (Global: Current Path) module.

Provides a Views field that displays the URL of the current page being viewed.

  • Nice module, but this is not what OP asked for. – leymannx Mar 4 at 9:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.