Drupal 8 - Create a module with a Hello World page

By xngo on March 8, 2019


Creating a module in Drupal 8 is not that hard. It is just that you have to be careful in adding the correct files in different places. It is so easy to make a mistake. A typo, wrong character case and spelling error will not work.

Define your module

  1. Create a directory with your module name and add it in ./modules directory. From now on, I will call my module tradesteps. Wherever you see tradesteps, replace it with your module name.
  2. Create ./modules/tradesteps/tradesteps.info.yml to tell Drupal what your module is. Here is an example:
name: Hello World Module
description: Creates a page showing "Hello World".
package: Custom

type: module
core: 8.x

Enable your module. That's it! You are done.

Create a hello world page

To display a page, you have to first define the URL path and then show the content of that path. In Drupal 8, defining an URL path is called routing. So, you have to create ./modules/tradesteps/tradesteps.routing.yml like the following:

  path: '/my_page'
    _controller: 'Drupal\tradesteps\Controller\MyPage::getContent'
    _title: 'Hello world'
    _permission: 'access content'
  • tradesteps.my_page is the routing name. You can change my_page to whatever you want. It should be lowercase and no space.
  • path is the URL path.
  • _controller defines which method to run. In this case, it is the getContent() method of class MyPage.

Now, you have to implement the MyPage class with the getContent() method. Add the following code in ./modules/tradesteps/src/Controller/MyPage.php and create the missing directories, i.e. src/Controller.

// Note: The namespace path doesn't contain 'src' because
//  by default, Drupal will fetch all source code files from 'src' directory.
namespace Drupal\tradesteps\Controller;
class MyPage {
  public function getContent() {
    return array(
      '#type' => 'markup',
      '#markup' => t('Hello world'),

Display a hello world page

  1. Clear your cache.
  2. Open http://your-domain.com/my_page

Hello Worl page


  • Clear your cache for ANY changes in codes!
  • Check message log for errors.


  • https://github.com/xuanngo2001/drupal-module-simple

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.