How can you contact us

2By phone at +40 749 014 360

If you still have problems, please let us know, by sending an email to Thank you!


Mon-Fri 9:00AM - 6:00AM
Sat - 9:00AM - 1:00PM
Sundays by appointment only!

Drupal 8 - How to attach css/js to a custom template file

/ / Drupal 8

In Drupal 8 it is easy to attach a cs/js to a template file.

We need to define a library that will contain the js/css files needed.

The libraries are defined in the file mymodule.libraries.yml
There, we define the each library with their js, css and dependencies of other libraries.

    js/mymodule.accordion.js: {}

    - core/jquery.ui.accordion

      css/mymodule.accordion.css: {}

We have defined our library as 'mymodule.accordion' and contains the js: js/mymodule.accordion.js, css: css/mymodule.accordion.css and a dependency of jQuery Accordion that is defined in drupal core.

Next, let's create the .js and .css files in /js, respecitvely /css folders.

The .js files "js/mymodule.accordion.js" will contain a simple call to jQuery accordion function.

(function($) {
  $(document).ready(function() {

In the css/mymodule.accordion.css, I've added a simple attribute for demo purposes:

#faq h3 {
  font-size: 18px;

Now, it's time to attach our library to our rendereable array.

   * Faq.
   * @return string
   *   Return Hello string.
  public function faq() {
    $build = array();

    // Load all FAQ nodes.
    $nodes = $this->entity_type_manager->getStorage('node')->loadByProperties(array('type' => 'faq'));

    $items = array();
    foreach ($nodes as $node) {
      // Add title and body to the list of items.
      $items[$node->id()] = array(
        'title' => $node->get('title')->value,
        'body' => $node->get('body')->value,

    // Render the 'faq' theme.
    $build['faq'] = array(
      '#theme' => 'faq',
      '#items' => $items,

    // Attach our custom  library
    $build['faq']['#attached']['library'][] = 'mymodule/mymodule.accordion';

    return $build;


Sign in your account to have access to different features

Forgot your details?