Data processing concepts in Drupal theming

lakshmi , Credit to  volkotech-solutions Jun 09

In Drupal, core modules and contribute modules serve up data that will be rendered on the page. Preprocess functions are used to change how that content is rendered and perform additional conditional logic and data processing of the variables present in a Twig template file. Preprocess functions are used to add and alter, the variables available in a template file.

The THEMENAME.theme file is used for data processing in the theme layer. Preprocess functions are placed in the THEMENAME.theme file, these are executed just before rendering a related Twig template file.

The complete list of preprocessing functions called for a template file is below, listed in the order they are called (if they exist):

  • template_preprocess(&$variables, $hook): Creates a default set of variables for all theme hooks with template implementations. Provided by Drupal Core.
  • template_preprocess_HOOK(&$variables): Should be implemented by the module that registers the theme hook, to set up default variables.
  • MODULE_preprocess(&$variables, $hook): hook_preprocess() is invoked on all implementing modules.
  • MODULE_preprocess_HOOK(&$variables): hook_preprocess_HOOK() is invoked on all implementing modules so that modules that didn't define the theme hook can alter the variables.
  • ENGINE_engine_preprocess(&$variables, $hook): This allows the theme engine to set necessary variables for all theme hooks with template implementations.
  • ENGINE_engine_preprocess_HOOK(&$variables): This allows the theme engine to set necessary variables for the particular theme hook.
  • THEME_preprocess(&$variables, $hook): This allows the theme to set necessary variables for all theme hooks with template implementations.
  • THEME_preprocess_HOOK(&$variables): Allows the theme to set necessary variables specific to the particular theme hook.

Let’s learn about hook_preprocess_HOOK() with some examples. Here ‘hook’ is a module or theme or template and HOOK is a page or block or node etc. For example, the theme name is simple.

 

Implements hook_preprocess_page()

In Drupal 8, you can utilize hook preprocess to attach libraries to any page based on any condition.

Example:- Implements hook_preprocess_page() can also be used to attach a library and to get the current language in the page.html.twig. Add the below code in simple.theme file.

/**
* Implements hook_preprocess_page() for PAGE document templates.
*/
function simple_preprocess_page(&$variables) {
 if ($variables['is_front'] == TRUE) {
   $variables['#attached']['library'][] = 'simple/global-styling';
 }

 $slanguage = \Drupal::languageManager()->getCurrentLanguage()->getId();
 $variables['language_using'] = $slanguage;
} 

Write a variable name in a page.html.twig.

{% if language_using == 'en' %}
  <h1>website displaying content in english language </h1>
{% else %}
  <h1>website not displaying content english language </h1>
{% endif %}

This isn't just applicable to the page. This fundamental model can be applied to any form of entity, including menu, taxonomy terms, blocks, paragraphs, custom entities, and so on.

Implements hook_preprocess_menu()

In Drupal 8, you can utilize hook preprocess to add classes to any menu based on any condition.

Example:-Add classes to the menu and write the following code in your simple.theme file.

/**
* Implements hook_preprocess_menu()
*/
function simple_preprocess_menu(&$variables) {
if ($variables['menu_name'] === 'main') {
 $variables['attributes']['class'][] = 'my-class';
}
$variables['added_class'] = 'added class as my-class';
}

Use a variable name in a menu.html.twig.

{{ added_class }}

This isn't just applicable to the menu. This fundamental model can be applied to any form of entity, including page, taxonomy terms, blocks, paragraphs, custom entities, and so on.

Implements hook_preprocess_node()

In Drupal 8, you can utilize hook preprocess to change the title of the node based on any condition.

Example: Add the suffix ‘you are the author’ to every node who logged in and to get taxonomy terms associated with a node.

use Drupal\taxonomy\Entity\Term;

/**
* Implements hook_preprocess_node()
*/
function simple_preprocess_node(&$variables) {
if ($variables['logged_in'] == TRUE && $variables['node']->getOwnerId() == $variables['user']->id()) {
 $variables['label']['#suffix'] =' [you are the author]';
}

$node = $variables['node'];
  if ($node->bundle() == 'content_type') {
    //- Array of terms
    $terms = [];
    $categories = $node->field_machine_name->getValue();
    foreach ($categories as $category) {
      $term = Term::load($category['target_id']);
     $result = $term->id();
      $terms[] = $result;
    }
    $variables['list_terms_id_variable'] = $terms;
  }

}

Use a variable name in a node.html.twig.

{{ list_terms_id_variable | render }}
{% for i in list_terms_id_variable %}
    <p>{{ i }}</p>
{% endfor %}

Implements hook_preprocess_block()

In Drupal 8, you can use hook preprocess to change the block's label based on any condition.

Example: Change label name of search block with caption.

/**
* Implements hook_preprocess_block()
*/
 
function simple_preprocess_block(&$variables) {
 if ($variables['plugin_id'] == 'search_form_block') {
   // change label name
   $variables['label'] = 'SEARCH FORM';
 }
$variables['caption'] = 'Please enter valid keywords.';
}

Use a variable name in a block.html.twig.

{{ label }}
{{ caption }}

Implements hook_preprocess_html()

In Drupal 8, you can utilize hook preprocess to add the body class based on the URL is possible.

Example: Add the body class based on the current path and add a custom view.

/**
 * Implements hook_preprocess_html().
 */
function simple_preprocess_html(&$variables) {
  // Get the current path.
  $current_path = \Drupal::service('path.current')->getPath();
  $internal_path = \Drupal::service('path_alias.manager')->getAliasByPath($current_path);

  // Add it to body class.
  $variables['attributes']['class'][] = str_replace("/", "", $internal_path);

  $variables['add_custom_view'] = views_embed_view('view_machine_name', 'block_machine_name');
}

Use a variable name in a html.html.twig.

{{ add_custom_view }}

Implements hook_preprocess_field()

In Drupal 8, you can use hook preprocess to change the field label based on any condition.

Example: Change label name of tag field.

/**
 * Implement hook_preprocess_field().
 */
function simple_preprocess_field(&$variables) {
  if ($variables['element']['#field_name'] == 'field_tags') {
    // change label name of tag field.
    $variables['label'] = 'custom tag name';
  }
  $variables['heading'] = 'Changed label name tag to custom tag name.';
}

Use a variable name in a field.html.twig.

{{ heading }}
{{ label }}

Implements hook_preprocess_paragraph()

In Drupal 8, you can utilize hook preprocess to add classes to any paragraph based on any condition.

Example:-Add classes to the paragraph and write the following code in your simple.theme file.

/**
 * Implements hook_preprocess_paragraph().
 */
function simple_preprocess_paragraph(&$variables) {
  $paragraph= $variables['elements']['#paragraph'];
  if ($paragraph->getType() === 'paragraph_types') {
    $variables['attributes']['class'][] = 'paragraph_types_class';
   }
  $variables['added_class'] = 'added class as paragraph_types_class ';
}

Use a variable name in a paragraph.html.twig.

{{ added_class }}

Implements hook_preprocess_comment()

In Drupal 8, you can utilize hook preprocess to change the date format for comment.

Example:-Display message author comments by how much time ago.

/**
 * Implements hook_preprocess_comment().
 */
function simple_preprocess_comment(&$variables) {
  //Get the author name.
  $variables['author'] = $variables['comment']->getAuthorName();
  // Getting the node creation time stamp from the comment object.
  $date = $variables['comment']->getCreatedTime();
  // Here you can use drupal's format_date() function, or some custom php date formatting.
  $variables['created'] = \Drupal::service('date.formatter')->formatInterval(REQUEST_TIME - $date);

  $variables['submitted'] = t('@username', ['@username' => $variables['author'] . ' commented ' . $variables['created'] . ' ago.' ]);

}

Write a variable name in comment.html.twig.

{{ submitted }}

Output: admin commented 15 min 35 sec ago.

These are some examples of implemented hook preprocess functions in drupal.

Conclusion:

Preprocess functions are used to change how that content is rendered and perform additional conditional logic and data processing of the variables present in a Twig template file. A preprocess function builds or alters variables and renders arrays Before they're rendered and/or provided to a template,

Comments