Drupal 8

Drupal 8: Custom Ordering Of Comments

Drupal 8's comment system has the ability to be threaded so that users can reply directly to other users comments and create threads of conversation. I have always found this difficult to use and difficult to read so I wanted to turn it off when I set up this site. The only issue I had was I could turn off the threading but couldn't alter the ordering of the comments.

The default ordering of comments in Drupal 8 is by thread. This means that even if you turn off threading the comments are always displayed in thread order. The CommentDefaultFormatter class is used by Drupal to display comments and contains this line of code.

Drupal 8 : How To Avoid Block Caching

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.

Drupal 8: Detecting An Anonymous User

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:

if (\Drupal::currentUser()->isAnonymous()) {
  // Run action.
}

 

Drupal 8: Get The Current Language

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

Drupal 8: Include A Twig Template

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.