The purpose of this post is to build a basic "Hello World Drupal" module in Drupal 8 porting the Acme Demo Bundle from Symfony 2 as a Drupal 8 module.
You can see the files and their content below.
Directory structure and files on this module
acme/
├── acme.info.yml
├── acme.module
├── acme.routing.yml
├── lib
│ └── Drupal
│ └── acme
│ └── Controller
│ └── DemoController.php
└── templates
├── base.html.twig
└── hello.html.twig
acme.module
<?php
// Drupal needs this file even if is empty
acme.info.yml
name: Acme
type: module
description: 'Acme Demo Module'
package: Sample
core: 8.x
acme.routing.yml
acme_hello_name:
path: '/acme/hello/{name}'
defaults:
_content: '\Drupal\acme\Controller\DemoController::helloAction'
_title: 'Acme Demo Module'
requirements:
_permission: "view content"
lib/Drupal/acme/Controller/DemoController.php
<?php
namespace Drupal\acme\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Template\TwigEnvironment;
/**
* DemoController Controller
*/
class DemoController extends ControllerBase implements ContainerInjectionInterface {
/**
* @var TwigEnvironment
*/
protected $twig;
/**
* Constructor
*
* @param TwigEnvironment $twig
*/
public function __construct(TwigEnvironment $twig) {
$this->twig = $twig;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static($container->get('twig'));
}
/**
* helloAction
*
* @param String $name
*/
public function helloAction($name) {
$twigFilePath = drupal_get_path('module', 'acme') . '/templates/hello.html.twig';
$template = $this->twig->loadTemplate($twigFilePath);
return $template->render(array('name' => $name));
}
}
/modules/acme/templates/hello.html.twig
{% extends '/modules/acme/templates/base.html.twig' %}
{% block basic %}
<h1>Hello {{ name }}!</h1>
{% endblock %}
/modules/acme/templates/base.html.twig
<div class="acme-hello-base">
{% block basic %}
<h1>No override data yet...</h1>
{% endblock %}
</div>
How to use and test it: Clone repo at modules directory located at the root of your Drupal Installation
$ cd drupal8.dev/modules
$ git clone https://github.com/hechoendrupal/acme.git
Enable module using drush