Back

Adding a Slider programmatically in Drupal 8

Developers are often tasked with adding a slider to a site—most often, to the front page. In this post, I will talk about how to add a slider to a home page in Drupal 8.

Our task will be adding a full-width slider containing some text to each picture. The main benefit of this slider is that you can manage the slider through the admin panel. You only need to add new materials of the “slider image” content type, upload a picture, and write the text. That’s all!

In addition, you can improve functionality by adding image sorting. To do this, you can add a new weight field to the content type and use it to order the images in the slider.

In this post I show only the back-end side of creating a slider and don’t discuss the front-end side. The main goal here is to show how to programmatically create a slider on Drupal 8.

To go about adding a slider, I have the following plan:

  1. For a slider, we will use the Slick responsive carousel jQuery plugin.
  2. For slider items, we will create the custom content type “Slider image”. It allows users to add and/or remove images to/from the slider. In addition, we can write individual text for each slider’s image.
  3. Coding: we will modify the front page’s Twig template to add the slider there, and I will add code to the theme file.

PREPARATORY STAGE

We will start out with a custom theme that I will call project_theme. It’s based on the Bartik theme. You can generate a new theme using drupal console (https://drupalconsole.com/). The Drupal console is a powerful instrument that lets you create pretty much everything (theme, modules, plugins, forms, etc.) in Drupal 8. It helps us save time because it generates code automatically—you don’t need to write code.

We will use the project_theme.theme file to work with $variables for the transmission of values from the code to the template.

STEP 1

We will want to download the slick archive and unpack it in the theme directory /theme/custom/project_theme/includes/. After that, we will need to connect our site with the library. To do this, let’s create the file project_theme.libraries.yml

home_page_slider:
  version: 1.x
  js:
    js/front.js: {}
    libraries/slick/slick/slick.min.js: {}
  css:
    theme:
      css/bootstrap.min.css: {}
      libraries/slick/slick/slick.css: {}
      css/front.css: {}
  dependencies:
    - core/jquery

Take a look at front.js. This file has the code for initializing the slick slider (more info at http://kenwheeler.github.io/slick/#settings)

(function ($) {

  Drupal.behaviors.initSlider = {
    attach: function (context, settings) {

      $(document).ready(function(){
        $('.slick-slider').slick({
          dots: true,
          speed: 800,
          autoplay: true,
        });
      });

    }
  };

})(jQuery);

Here is a little additional explanation for what we have above:

slick.min.jsslick.css. These are the Slick library files.
bootstrap.min.css. In the slider html tags I used some bootstrap classes. Therefore, I added this file to the library.
front.css. These are custom css rules for changing the default Slick slider styles. For example, we can change the arrow style, Slick-dots style, add styles for text, stretch the image to full-screen width, add an icon font, etc.

STEP 2

We will now create custom content type. For this, we will need to go to /admin/structure/types/add
create new content type

Let’s write a name to our content type (here: Slider image) and set the description. Under the Publishing option tab, uncheck “Promoted to front page.” In the Menu settings tab, uncheck all items.

Then let’s go to the new content type we just created and add an “Image” field, then set the label to “slider_image”.

set label for image field

Now, in the slider_image content type we have to fields:

  1. Body. This is for setting the image text.
  2. Image. This is for uploading an image to the slider.

We can create some new materials for the Slider image content type.

create content

Let’s do this and go to the next step.

STEP 3

At last, we have come to the point where we need to write code!

Let’s begin by creating a new Twig template with the Bartik theme based on page.html.twig. We will copy this Twig template from the Bartik theme into the /theme/custom/project_theme/templates/layout/ directory and rename it page–front.html.twig. This will change the default home page template to the one we are modifying.

Before editing this file, let’s insert some code to the project_theme.theme file. We will add the new variable home_page, which contains data about the slider images.


/**
 * Implements hook_preprocess_page() for page.html.twig.
 */
function project_theme_preprocess_page(array &$variables) {

  // If page is front, add to the $variables values for twig template
  if ($variables['is_front']) {

    // Create data for slider
    // Get from DB nids of content type slider_image
    $query = \Drupal::database()->select('node', 'n');
    $query->fields('n', ['nid']);
    $query->condition('n.type', 'slider_image');
    $nids = $query->execute()->fetchAll();

    $variables['home_page']['slides'] = array();
    
    // get and set values from content type to variable
    foreach ($nids as $val) {
      $node = Drupal\node\Entity\Node::load($val->nid);

      $text = $node->get('body')->getValue();
      $img = $node->get('field_slider_image')->getValue();

      $file = \Drupal\file\Entity\File::load($img[0]['target_id']);
      $img_src = $file->url();

      $variables['home_page']['slides'][] = array(
        'text' => $text[0]['value'],
        'img_src' => $file->url(),
      );
    }
    
  }
}

In the front-page template, before
<div id="main-wrapper">,
we will insert the following code (this is the slider construction code):

{{ attach_library('project_theme/home_page_slider') }}

    <div class="b-carousel slick-slider slick-dotted">
      {% for slide in home_page.slides %}
        <div class="b-carousel__slide" 
style="background: url('{{ slide.img_src }}'); 
background-position: 50% 50%; 
background-repeat: no-repeat; 
background-size: cover;">
          <div class="container">
            <div class="col-sm-8 col-sm-offset-2">
              <div class="b-example">
                <div class="b-example__item b-example__item_iwill">
                  <div class="b-example__label">S&F</div&lgt;
                  <div class="b-example__text">{{ slide.text }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      {% endfor %}
    </div>

In the first string, I have attached our library, which I define in project_theme.libraries.yml file, to the page. It includes all the necessary .js and .css files to correctly display our slider. After this, I added the slider construction. As you can see, I used the home_page variable, which I added in the template_preprocess_page function. I looked over all the slides and created the slider.

The Twig templates allow us to work with variables. It’s a great new opportunity in Drupal 8. You don’t need to write any php code in a template: you can simply use the native Twig templates methods for this! For more information, see the documentation at http://twig.sensiolabs.org/.

That’s it! Now you can go to the home page and see the results.

slider_res