CHAPTER 6

image

Adding CSS to Your Drupal Module

By using CSS (Cascading Style Sheets), you have the ability to give your Drupal web pages their own custom look. In this chapter, you will add CSS, which will add color and styling to your Hello World module.

Image Note  The code for this Drupal module is on Github: https://github.com/barnettech/drupal8_book/tree/with_css.

Using CSS Within Your

We’re going to add to the hello_world basic module you created earlier by adding some color and styling to the page with CSS. We’ll be adding some CSS to add a background image to our HTML, and we’ll change the font color and size of some other HTML elements within our page.

Following are the updated files needed in our hello_world module with the newly added CSS.

The hello_world.info.yml will still contain the following:

name:  Hello World
type:  module
description:  'A basic Drupal 8 Hello World Module.'
package:  Custom Modules
version:  1.0
core:  8.x

You will need to create a hello_world.permissions.yml file. This version of the Hello World page will be gated with a new permission, which you’ll create in this hello_world.permissions.yml file. This file defines a new permission: view hello world. To view this web page in this version, you’ll need to give users permissions on the Drupal permissions page (see Chapter 2, where we covered granting user permissions; look on the permissons page for the new permission “view hello world”).

The hello_world.permissions.yml file looks as follows:

view hello world:
  title: 'View hello world'
  description: 'Allow access to view the hello world page.'
  restrict access: TRUE

The hello_world.routing.yml file remains the same and looks like this. Again, this file maps URLs (uniform resource locators) to what code to run and display on the page.

hello_world_settings:
  path:  '/hello/world'
  defaults:
    _controller:  'Drupalhello_worldControllerHelloWorldController::
myCallbackMethod'
    _title: 'Hello World'
  requirements:
    _permission: 'view hello world'
  1. Add a folder called css within the hello_world directory, and then add a folder called images within the css folder.
  2. Within the css folder you just created, add the CSS file called hello_world.css with the following code:
    .myDiv {
        position: relative;
        z-index: 1;
    }

    .myDiv .bg {
      position: absolute;
        z-index: -1;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        background: url(images/scribble.jpeg) center center;
        opacity: .2;
        width: 100%;
        height: 100%;
    }

    .block-title {
      font-size: large;
      color: red;
    }
  3. Add a new file hello_world.libraries.yml or your_module_name.libraries.yml, which contains the following code:
hello-world:
version: 1.x
css:
  theme:
    css/hello_world.css: {}

This file and the code within define any CSS and JavaScript libraries you’ll use in your module. In this chapter you’ll focus on adding CSS; Chapter 8 covers adding JavaScript to Drupal.

Next, in the HelloWorldController.php file you’ll call this library in your render array. This will add the CSS your HTML will use.

Your HelloWorldController.php file should now look this. Note that some extra HTML has been added, which is not highlighted. The line where you add your CSS file is highlighted. Also notice the added divs and classes to the HTML; the new class names have been highlighted as well.

<?php
     /**
      * @file
      * Contains Drupalhello_worldHelloWorldController.
      *

     namespace Drupalhello_worldController;

     /**
      * Provides route responses for the hello world page example.
      */
     class HelloWorldController {
       /**
        * Returns a simple hello world page.
        *
        * @return array
        *   A very simple renderable array is returned.
        */
       public function myCallbackMethod() {
         $content = '
         <div class="myDiv">
           <div class="bg"></div>
            <div class="block-title">A basic Drupal page
            created programmatically, Hello World</div>

             Some random text to show off this transparent
        background ....
             Lorem ipsum dolor sit amet, consectetur adipiscing
        elit. Morbi nisi purus, gravida sit amet molestie
        et, facilisis vel nulla. Mauris faucibus augue eu
        quam feugiat at lacinia velit malesuada. Sed
        bibendum faucibus mattis. Maecenas quis ligula
        nibh, sit amet iaculis metus. Aenean lobortis
        massa ut nulla tristique eu vestibulum leo
        eleifend. Maecenas arcu lectus, facilisis in
        mattis sed, pretium et metus. Phasellus elementum,
        elit fringilla mollis sollicitudin, ipsum odio
        vestibulum quam, vitae tristique odio tortor eu
        augue. Pellentesque volutpat placerat neque, sit
        amet vehicula lectus commodo vitae. Aliquam nec
        ultricies eget libero. Donec mollis malesuada est
        a varius. Vestibulum dignissim venenatis nisl, nec
        semper massa tincidunt egestas. Maecenas a erat sem.

             Vestibulum semper eleifend eros at semper. Phasellus
        neque augue, eleifend ut congue pharetra, sagittis
        in neque. Duis sit amet es et risus sodales vulputate
        sed ut sapien. Vestibulum consequat est lobortis
        ligula aliquam ac sodales ante sodales. Fusce dict
        um tortor ut est vehicula sit amet imperdiet dolor
        consequat. Maecenas nec risus sed quam accumsan
        vestibulum id ac urna. Suspendisse suscipit dictum
        dolor condimentum rutrum. Duis augue sem, mattis
        vel tincidunt ut, interdum in mauris. In quis
        feugiat ipsum. Donec euismod massa et tortor
        rhoncus lacinia. Nunc felis ligula, tincidunt eu
        viverra at, auctor quis magna.

             Nullam sapien augue, venenatis sit amet ornare et,
        blandit nec velit. Morbi eu ligula a lacus commodo
        lacinia vel et neque. Sed at nisi at sapien adipiscing
        accumsan in fringilla ligula. Nunc fringilla, est vel
        ullamcorper tincidunt, tellus ligula lobortis turpis,
        vel gravida purus lacus a dui. Quisque et massa
        vestibulum nisi dictum lacinia vehicula ac nisi. Nulla
        facilisi. Cum sociis natoque penatibus et magnis dis
        parturient montes, nascetur ridiculus mus. Phasellus
        sed neque ante, venenatis sagittis dui. Cras lorem
        ipsum, scelerisque tempor aliquet quis, imperdiet in
        augue. Curabitur tellus est, ultrices eu sagittis et,
        pellentesque id enim. Nunc lobortis mattis viverra.
        Sed non purus ipsum. Aenean ac justo sed urna eleifend
        consequat.
         </div>';
         $element = array(
           '#markup' => '<p><b>Saying Hello World in Drupal 8
           is cool!</b></p>' . $content,
           '#attached' => array(
             'library' => array(
               'hello_world/hello-world',
             ),
           ),
         );
         return $element;
       }
     }

Within the bold code you just added to the $element array, add the following lines:

$element = array(
      '#markup' => '<p><b>Saying Hello World in Drupal 8
      is cool!</b></p>' . $content,
      '#attached' => array(
        'library' => array(
          'hello_world/hello-world',
        ),
      ),
    );

These lines attach the CSS file hello_world.css, which lives in the library you created in your hello_world.libraries.yml page, to this HTML page. Notice you added the library by adding 'hello_world/hello-world'—this being the module name, then a slash, and then the library name.

Find your own background image and download it into the images folder you created. You can call the file anything you like; I called mine scribble.jpeg—just make sure to replace the name scribble.jpeg with your file’s name. Figure 6-1 shows my work to this point. You can see that I’ve successfully added some CSS to make the Drupal module a bit more stylish.

9781430264668_Fig06-01.jpg

Figure 6-1. The resulting web page after adding some CSS to the Hello World Drupal module

Summary

In this chapter you’ve seen just how to use CSS to decorate your Drupal web pages. You also learned how to add CSS to a custom-created Drupal module.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset