Getting Drupal8 Config and Variable Info with Twig and/or PHP

Drupal8, Symphony2, Twig and PHP - so happy together?
Drupal8, Symphony2, Twig and PHP - so happy together?

OK, so here we are. Drupal 8 and Twig. No longer can you do things like drupal_get_title() and instead you have to pull variables through a more stringent Model-View-Controller arrangement, specifically Drupal8/Symfony2 and the Twig templating engine. And many Drupal7 commands are gone, so you have to use the object-oriented approach to get information directly in PHP. So here is a progressively-building cheat-sheet of how to pull certain configs and variables using PHP and/or Twig variables specific to Drupal 8:


Get the Drupal8 Site Name and Slogan in PHP

  $site_name =  \Drupal::config('system.site')->get('name');
  $site_slogan =  \Drupal::config('system.site')->get('slogan');



See what methods and info are inside Drupal8 objects
Here's a PHP example of peering inside a Drupal8 object (in this case the site configuration) to see what methods it supports:
$thing = \Drupal::config('system.site');
var_dump( get_class_methods($thing) );  // shows methods supported

You can also show information (variables) inside classes or objects like this:

var_dump( get_class_vars($thing) );  // this would be for a class, or
var_dump( get_object_vars ($thing) );  // for a an object, etc...

...and in PHP versions 5.6 and above, you can use the magic function __debugInfo() too:
http://php.net/manual/en/language.oop5.magic.php#object.debuginfo



Get the current User ID in Drupal 8
Yes, in Drupal 7 you could call a global $user object and just pull a $user->id but those days are gone. Try this instead:

  print \Drupal::currentUser()->id();

More to come...

Tags: