How to create custom twig template and render data in custom twig file in Drupal 8 and 9

Here we are going to create a twig template in our custom module and loading data in that twig file with controller.

Here dn_studentslist is our custom module name.

Step 1

Create below rout in dn_studentslist.routing.yml file.

Step 2

Create below theme hook in order to define template name and variables in twig files.

Here students_list is the template name. students and title are variables. you have to create students-list.twig.html files in templates folder.

Step 3

Here we are populating the variables in controller.

As you can see above, variables are populated and returns with template name.

Step 4

Create below file in module template folder.

\templates\students-list.html.twig

provide below content. Here we are displaying students details by iterating through students object.

So final table will look like as below.

Step 5

For adding style to your html table, create below file.

Create a css folder and place below content in style.css.

And now update twig template, students-list.html.twig as below. Here we are attaching css library  in order to import style.css

Clear the cache and access the page  /list/students.

Table will be look like as below.

Download sample source code here.

Get Free E-book
Get a free Ebook on Drupal 8 -theme tutorial
I agree to have my personal information transfered to MailChimp ( more information )
if you like this article Buy me a Coffee this will be an ispiration for me to write articles like this.

You may also like...