6

I'm attempting to retrieve a GET request variable for use in a twig template. For instance if you go to the page myurl.com/node/64?name=Dave I want the page to render

<h1>Dave</h1>

However I'm having trouble retrieving this variable. I've attempted

<h1>{{app.request.get('name')}}</h1>

In my twig template but it turns up empty. How would I retrieve a GET variable from within a twig template?

11

You didn't say what template this is for, but app is not defined in any of the templates I have seen.

What you could do, is add a theme_preprocess_TEMPLATE function to include the GET params. Here is a page template example:

In your mytheme.theme file, add a hook_preprocess_page function.

/**
 * Implements hook_preprocess_page()
 */
function MYTHEME_preprocess_page(&$vars) {
  $vars['get']['name'] = $_GET['name'];
}

Then in your page.html.twig you can render it like this:

<h1>{{ get.name }}</h1>
  • My template is actually a block template and I can't seem to get access to the variable from preprocess_page. I tried doing the same thing in preprocess_block but the block template can't seem to see any variable I create for it. – Matt Oct 14 '16 at 20:36
  • Did you rebuild the cache after adding the hook? – Chance G Oct 14 '16 at 20:37
  • yes. As I test I did mymodule_preprocess_block(&$variables){ $variables['test'] = 'testing'; } and inside my template {{ test }} but it came out null. I tried it as $variables and $vars. – Matt Oct 14 '16 at 20:39
  • 2
    If you add your own template called newsarchive, then it's ...preprocess_newsarchive, not block. – Berdir Oct 14 '16 at 21:04
  • 3
    Note that in this case, I would actually recommend you just pass along that from the request object in your block: #name => \Drupal::request()->query->get('name'), make sure you define it as well in your hook_theme(). And last note, the xss filtering is not needed, that would only result in double escaping. auto-escape takes care of that – Berdir Oct 14 '16 at 21:14

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.