Tos Web Developer provides insights, tutorials, and advice around topics including content strategy, design, Drupal Development, Drupal Custom Module Development, Drupal 8 Custom themes, PHP, Server, Twig, and more


Example 1

Create mymodule.module file

 /**  
  * Implements hook_theme() to add the template definition.  
  **/  
 function mymodule_theme($existing, $type, $theme, $path) {  
   return array(  
     'mymodule_template' => array(  
       'variables' => array('test_var' => NULL),  
     ),  
   );  
 }  
PHP

Create src/Controller/MyModuleController.php file

 <?php  
 namespace Drupal\mymodule\Controller;  
 use Drupal\Core\Controller\ControllerBase;                                            
 class MyModuleController extends ControllerBase {  
   public function content() {  
     return array(  
       '#theme' => 'mymodule_template',  
       '#test_var' => $this->t('Test Value'),  
     );  
   }  
 }  
PHP

Create in the templates folder the mymodule-template.html.twig file

<p> This is the lotus template with a value of {{ test_var }} </p>

Example 2


I will use the two examples below to show you how to add a custom template to our tosweb_controller module.

Create  hook_theme() in codimth_controller.module  

<?php 
/**  
  * @param $existing  
  * @param $type  
  * @param $theme  
  * @param $path  
  * @return array  
  */  
 function tosweb_controller_theme($existing, $type, $theme, $path) {  
   return [  
     'tosweb' => [  
       'variables' => ['users' => NULL],  
     ],  
   ];  
 }  
PHP

 

Create src/Controller/ToswebController.php file

<?php
 namespace Drupal\tosweb_controller\Controller;  
 use Drupal\Core\Controller\ControllerBase;  
 use Drupal\user\Entity\User;  
 class ToswebController extends ControllerBase  
 {  
   public function index()  
   {  
     $userlist = [];  
     $ids = \Drupal::entityQuery('user')  
       ->condition('status', 1)  
       ->condition('roles', 'administrator')  
       ->execute();  
     $users = User::loadMultiple($ids);  
     foreach ($users as $user) {  
       $username = $user->get('name')->getString();  
       $mail = $user->get('mail')->getString();  
       $userlist[] = ['mail' => $mail, 'username' => $username];  
     }  
     return array(  
       '#theme' => 'tosweb',  
       '#users' => $userlist  
     );  
   }  
 }  
PHP

 

Create twig template templates/tosweb.html.twig 

 <p>Test twig template!</p>                                         
 {% for user in users %}  
   <p>{{ user.mail }}: {{ user.username }}</p>  
 {% endfor %}  

No comments:

Post a Comment

| Designed And Blog Post by www.toswebdeveloper.com