Drupal 8

Posts, reviews and snippets about Drupal 8.

Drupal 8 : How To Avoid Block Caching

Sunday, February 11, 2018 - 18:21

I was struggling with a problem on a Drupal 8 project that was in development recently where a block used to show information to anonymous users was cached for the first user who saw it. This meant that the special message meant for the first user was then being seen by all subsequent users who visited that page. This only happened when page caching was turned on, but as it's best practice to do that I didn't want to turn that off just to solve one little problem.

Category: 

Drupal 8: Detecting An Anonymous User

Tuesday, June 28, 2016 - 10:38

To find out if the current user is anonymous use the following.

\Drupal::currentUser()->isAnonymous();

This can be used as part of an if statement like this:

Category: 

Drupal 8: Get The Current Language

Tuesday, April 26, 2016 - 16:27

To get the currently selected language on a Drupal 8 site you need to run the following.

$language = \Drupal::languageManager()->getCurrentLanguage()->getId();

This will return the 2 character ISO language code for the language. So for English this would be "en".

To get the language name instead of the language code use this.

$language =  \Drupal::languageManager()->getCurrentLanguage()->getName();
Category: 

Drupal 8: Include A Twig Template

Friday, April 1, 2016 - 16:01

When creating re-usable theme templates in Drupal 8 it's quite easy to include that template by using the following snippet.

{% include directory ~ '/templates/parts/footer.html.twig' %}

This assumes that your footer.html.twig template file is kept in the same theme as the template you are working on. It's also good practice to add the template part to a directory called 'parts' or 'components' to separate them from the normal Drupal templates.

Category: