logo

CUstom code if else condition in twig template drupal 8

15
February

CUstom code if else condition in twig template drupal 8
By: Anonymous | Published On: Wed, 02/15/2023 - 20:55

In Drupal 8, you can use the {% if %} statement to create if-else conditions in Twig templates. Here's an example:

{% if condition %}
  // Code to execute if the condition is true.
{% else %}
  // Code to execute if the condition is false.
{% endif %}

Replace "condition" with your desired condition to evaluate. You can use logical operators such as and, or, and not to create more complex conditions.

Here's an example of how you might use this in a Drupal 8 Twig template to display a message if the current user is authenticated:

{% if logged_in %}
// Code to execute if logged in is true.

{% else %}

// Code to execute if not logged in.

{% endif %}

In this example, logged_in is a boolean variable that is set to true if the current user is authenticated, and false if they are not. The {{ current_user.name }} variable is used to display the current user's name if they are logged in.

Need Help ?