use Drupal\node\Entity\Node; use Drupal\file\Entity\File; use Drupal\Core\Template\TwigExtension; use Twig\TwigFunction; /** * Implements hook_theme(). */ function niti_theme() { return [ 'mytheme_sample_template' => [ 'variables' => ['my_variable' => NULL], ], ]; } /** * Implements hook_preprocess_page(). */ function niti_preprocess_page(array &$variables) { // Load Homepage Banners $banner_nids = \Drupal::entityQuery('node') ->condition('type', 'homepage_banners') ->condition('status', 1) ->sort('created', 'DESC') ->execute(); $banner_nodes = Node::loadMultiple($banner_nids); $banners = []; foreach ($banner_nodes as $node) { if ($node->hasField('field_banners_image') && !$node->get('field_banners_image')->isEmpty()) { $image = $node->get('field_banners_image')->first(); $file = File::load($image->target_id); if ($file) { $banners[] = [ 'url' => file_create_url($file->getFileUri()), 'alt' => $image->get('alt')->getString() ?? '', 'title' => $node->label(), ]; } } } $variables['homepage_banners'] = $banners; } /** * Implements hook_preprocess_node__whats_new(). */ function niti_preprocess_node__whats_new(array &$variables) { $nids = \Drupal::entityQuery('node') ->condition('type', 'whats_new') ->condition('status', 1) ->sort('created', 'DESC') ->range(0, 5) ->execute(); $nodes = Node::loadMultiple($nids); $whats_new_items = []; foreach ($nodes as $node) { $link_url = ''; $link_title = $node->label(); // Default title if ($node->hasField('field_link') && !$node->get('field_link')->isEmpty()) { $link_item = $node->get('field_link')->first(); $link_url = $link_item->getUrl()->toString(); if (!empty($link_item->title)) { $link_title = $link_item->title; } } $whats_new_items[] = [ 'title' => $link_title, 'url' => $link_url, ]; } $variables['whats_new_items'] = $whats_new_items; } /** * Twig Extension to add custom Twig function. */ namespace Drupal\niti\TwigExtension; use Drupal\Core\Template\TwigExtension; use Twig\TwigFunction; class MyTwigExtension extends TwigExtension { /** * {@inheritdoc} */ public function getFunctions() { return [ new TwigFunction('generateCourseCardSec2022', [$this, 'generateCourseCardSec2022']), ]; } /** * Custom function to generate the course card. */ public function generateCourseCardSec2022($node) { // Custom logic to generate the course card. // Example: Return an HTML snippet with course details. if ($node instanceof Node && $node->hasField('field_course_description')) { $description = $node->get('field_course_description')->value; return "

{$node->label()}

{$description}

"; } return "
Invalid Course
"; } } Niti Aayog TOC November 2023 | NITI Aayog

Tags

Most Popular

TOC November 2023

Recent Posts

Recent comments

No comments available.