9

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?

2 Answers 2

16

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>
12
  • 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.
    – Amy
    Oct 14, 2016 at 20:36
  • Did you rebuild the cache after adding the hook?
    – Chance G
    Oct 14, 2016 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.
    – Amy
    Oct 14, 2016 at 20:39
  • 2
    If you add your own template called newsarchive, then it's ...preprocess_newsarchive, not block.
    – Berdir
    Oct 14, 2016 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, 2016 at 21:14
0

You can create a Twig function to achieve this. E.g:

namespace App\Twig;

use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

class AppExtension extends AbstractExtension
{
    public function getFunctions()
    {
        return [
            new TwigFunction('getQueryArg', [$this, 'getQueryArg']),
        ];
    }

     
    public function getQueryArg(string $argName): string|int {
      return \Drupal::request()->query->get($argName);
    }
}

In TWIG you would call it as: {{ getQueryArg('name') }}

See https://symfony.com/doc/current/templating/twig_extension.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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