To avoid creating html directly in the PHP code. In drupal 8 you can use twig templates. To create new twig templates in your module, go through the following steps.
1. Define hook_theme in .module file
Create a modulename.module
file, and add code that defines each of your twig templates;
2. Call the Template
You can make a call to your twig template from a controller method that is called from your router yml
file.Below is an example function that is called from the routing yml
file in the module.
3.Create Twig Template
In your module, inside of the templates folder, create your twig template. The name of the file has to match what you put into hook_theme()
(replace underscores with dashes)
. In this case, the filename would be json-parser.html.twig
.
Here is the file I used :
A great way to attach a library is to directly add it in a template file. Drupal 8 has a special function called attach_library() just for this purpose.
4.Creating Libraries
In Drupal 8 we can manage all css and js files using libraries defined in a .libraries.yml file, added to your theme.Each library defined in this file includes a unique name, any number of CS or JS files, dependencies, and other information needed to define the properties of the library.
Here is an example of a library file:
The file is in YAML
format, which Drupal 8 uses for all configuration files. It should be named using the name of your theme, just like your .info.yml
file. Let’s get a better understanding of each line.
5.Naming
Each library is given a custom name. This name can be anything, but must be unique to the module or theme that supplies it.
6.Header
Setting the header property to true, to indicate that the js
files in that library are in the 'critical path'
and should be loaded from the header. Any direct or indirect dependencies of libraries declared in this way will also automatically load from the header, you do not need to declare them individually for them to be available. By default, all JS
files are loaded in the footer.
7.Javascript
We add JavaScript files below the js: line, with each file on a separate line. You can set additional properties inside the curly braces following the file name. For example, adding minified: true will tell Drupal this file has already been minified, so don’t try to minify it again when aggregating the files.
8.Dependencies
The dependencies: line is where you add any libraries your library requires. This must be other libraries already defined by your theme, some module, or Drupal core.
9.CSS
All CSS files are included below the css: line
10.External Files
We can link to external stylesheets by simply supply the external URL for retrieving the file, and set the external property to true as shown in the above library.
Thus you can create themes in drupal 8 using twig template.