manniru
5/6/2014 - 5:52 PM

Drupal 8 example: How to render a Twig template and load a CSS file from a Controller

Drupal 8 example: How to render a Twig template and load a CSS file from a Controller

<div class="acme-hello-text">
  <h1>Hello {{ name }}!</h1>
</div>
acme_hello:
  path: '/acme/hello/{name}'
  defaults:
    _content: '\Drupal\acme\Controller\DefaultController::hello'
    _title: 'acme Title'
  requirements:
    _permission: 'access content'
<?php

  function acme_theme() {
    $theme['hello_page'] = [
      'variables' => ['name' => NULL],
      'template' => 'hello'
    ];

    return $theme;
  }
.acme-hello-text {
  background-color: #dedede;
}
<?php

namespace Drupal\acme\Controller;

use Drupal\Core\Controller\ControllerBase;

class DefaultController extends ControllerBase 
{

  /**
   * hello
   * @param  string $name
   * @return string
   */
  public function hello($name) 
  {
    return [
      '#theme' => 'hello_page',
      '#name' => $name,
      '#attached' => [ 
        'css' => [
          drupal_get_path('module', 'acme') . '/assets/css/acme.css'
        ]
      ]
    ];
  }
}