Is this considered a good practice for rendering a Twig template and loading a CSS file from a controller?
DefaultController.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;
class DefaultController extends ControllerBase implements ContainerInjectionInterface
{
/**
* @var Drupal\Core\Template\TwigEnvironment
*/
protected $twig;
public function __construct(TwigEnvironment $twig)
{
$this->twig = $twig;
}
public static function create(ContainerInterface $container)
{
return new static(
$container->get('twig')
);
}
/**
* hello
* @param string $name
* @return string
*/
public function hello($name)
{
$template = $this->twig->loadTemplate(
drupal_get_path('module', 'acme') . '/templates/hello.html.twig'
);
$markup = [
'#markup' => $template->render([ 'name' => $name ]),
'#attached' => [ 'css' => [
drupal_get_path('module', 'acme') . '/assets/css/acme.css'
]
]
];
return drupal_render($markup);
}
}
acme.routing.yml
acme_hello:
path: '/acme/hello/{name}'
defaults:
_content: '\Drupal\acme\Controller\DefaultController::hello'
_title: 'acme Title'
requirements:
_permission: 'access content'
hello.html.twig
<div class="acme-hello-text">
<h1>Hello {{ name }}!</h1>
</div>
\Drupal::service('renderer')->renderRoot()
instead of deprecateddrupal_render()
.