Is there a way to get the user's IP address in a twig template? All the twig examples I find say to do it like this:

{% set ipAddr = app.request.server.get("REMOTE_ADDR") %}

But this variable always returns NULL. These examples aren't specific to Drupal so I'm guessing part of the Drupal implementation blocks/omits this.

  • Preprocess the template and get the IP that way? – Kevin Nov 30 '17 at 19:21
  • That's exactly the solution that I ended up going with as shown below. – Cloudkiller Nov 30 '17 at 21:59

Suppose you want to get the ip in the page.html.twig file.

in your


you can try

use Symfony\Component\HttpFoundation;

function YOURTHEME_preprocess_page(&$variables) {
  $variables['page']['ip'] = \Drupal::request()->getClientIp();


in your template


you can try:

{{ page.ip }}

  • That worked perfectly. I had just found the xxx.theme file and was working on a preprocess function when I saw your answer. Thanks! – Cloudkiller Nov 30 '17 at 20:00
  • This doesn't work for me because of drupal cache system... – Sky Dec 24 '17 at 23:36
  • As time has progressed I've noticed that @Sky is correct, Drupal will generate an IP the first time the template is loaded and then cache that IP. Any future users will see the cached IP instead of their own. – Cloudkiller May 24 '18 at 18:16

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.