Drupal 8 Themes

From Training Material
Jump to navigation Jump to search

THIS IS A DRAFT

This text may not be complete.


title
Drupal 8 Themes
author
Lukasz Sokolowski

Drupal 8 Themes

Drupal 8 Themes Training Materials


Drupal 8 Themes Introduction ⌘

"Themes allow you to change the look and feel of your Drupal site.
You can use themes contributed by others or create your own to share with the community.
Contributed themes are not part of any official release
and may not have optimized code/functionality for your purposes.
You can also create a sub-theme of an existing theme.
A sub-theme inherits a parent theme's resources."

Source: https://www.drupal.org/project/project_theme

Installing Existing(Contributed) Themes ⌘

Very similar way like installing modules.
We can do it:

  • manually from drupal.org
  • via command liners - drush or composer
  • in our website in configuration Appearance/Install new theme

After installation we can just Enable or Enable and set default in Appearance section in management menu.

Manual theme installation ⌘

MonkeyJob.jpg


Manually download the theme package and uncompress its content into /themes.
You can use browser and GUI(files navigator) or command line tools like wget and tar .

Exercise 1 ⌘

  1. Find Mayo theme in drupal.org site and install it manually
    • Play a while with it's plenty bunch of options
      • Add resizer to the header
      • Change logo picture into your favorite animal photo
      • Use different Font Family
      • Add rounded corners everywhere it's possible
      • Hide all sidebars, header and footers - leave just main content only
  2. Install Drupal 8 Parallax Theme, but via admin interface (Appearance)
  3. Install and enable Bootstrap theme via drush command

Modifying an existing Theme ⌘

Svn cp turtles.png


We can copy for example one of default Drupal core themes like Bartik or Stark.

Then place it into /themes, rename all convenient files and change files: css, templates, js, images, etc.

This is the simplest way to create our theme without much effort.

Exercise 2 ⌘

Let's create BlaBla theme.

Changes to do:

  • Copy Bartik theme from your_website/themes to your_website/themes
  • Find all instances of bartik name in all copied files and replace it with blabla
  • Make site name font 24px and site slogan red (style.css)

Subthemes ⌘

SubTheme.jpg


Themes which can inherit css, js, etc from base theme and override those files, partly or completely.

(https://www.drupal.org/theme-guide/8/creating-a-sub-theme)

Exercise 3.1. ⌘

  1. Create sub-theme with Bartik theme, call it Kitrab
    1. Create themes/kitrab folder
    2. Make file kitrab.info.yml
      name: Kitrab - my own drupal sub-theme
      type: theme
      description: This is a kitrab sub theme of Bartik
      core: 8.x
      base theme: bartik
      libraries:
        - kitrab/global-styling
      regions:
        header: Header
        featured: Featured
        content: Content
        sidebar_first: First sidebar
        sidebar_second: Second sidebar
        footer: Footer
      
    3. Add second file kitrab.libraries.yml
      global-styling:
        css:
          component:
            css/style.css: {}
      
    4. Inheriting Block Placement - config/install (look at the mayo example)
    5. Inheriting Block Templates - create file kitrab.theme
      /**
       * Implements hook_theme_suggestions_HOOK_alter for blocks.
       */
      function kitrab_theme_suggestions_block_alter(&$suggestions, $variables) {
      
        // Load theme suggestions for blocks from parent theme.
        foreach ($suggestions as &$suggestion) {
          $suggestion = str_replace('kitrab_', 'bartik_', $suggestion);
        }
      }
      

Exercise 3.2. ⌘

  1. Create sub-theme with Bootstrap theme:
    • Make sure Bootstrap theme is already enabled (drush en)
      • copy cdn from starterkits folder into /themes/
      • follow all necessary steps from the docs below:
        • bootstrap\docs\Sub-Theming.md
    • Override at least one css file in your sub-theme

Panels and other modules related to theming ⌘

ModulesTheming.jpg
  • Field Layout and Drupal Layout Builder
  • Responsive Image
  • Panels and Panelizer/Page Manager
  • Display Suite
  • Paragraphs

Field Layout ⌘

  • ATM has status experimental
  • The module applies predefined layouts to "entity displays"
    • Can be overridden on specific pages using Layout Builder
  • Allows us to arrange fields into regions on forms and displays of entities (nodes, users, etc)
  • Manages two separate layouts for entities: for view and for form displays
  • The layout control is in other modules
    • Layouts are found using modules in Layout Discovery
      • They have Twig files and CSS for layouts
  • Panelizer and similar modules can feed in layouts

Drupal Layout Builder ⌘

  • Currently experimental, expected to reach stability in Drupal 8.7 in the spring of 2019
  • Lets us define the layout of any fieldable entity type (content type, user, etc), or its individual entity
    • We just select from the predefined sections and add blocks and fields to them as we wish
  • The module’s UI is simple and intuitively understandable for administrators
    • It is equipped with the drag-and-drop feature to swap the blocks and shape our page
  • For developers - layouts can be defined in a module or theme and have Twig templates

Responsive Image ⌘

  • Outputs responsive images using the HTML5 picture tag
  • Provides
    • an image formatter
    • breakpoint mappings
  • Uses
    • Defining responsive image styles
      • Fallback image style
      • Breakpoint groups: viewport sizing vs art direction
      • Breakpoint settings: sizes vs image styles
      • Sizes field
      • Image styles for sizes
    • Using responsive image styles in Image fields

Panels and Panelizer/Page Manager ⌘

Panels module is a drag and drop content manager that

  • lets us visually design a layout
  • and place content within that layout

Panels con't ⌘

Panels

  • Allows a site admins to create customized layouts for multiple uses
  • Supports styles straight from the styleguide
  • Features a layout builder
  • Uses Contexts
  • Includes a pluggable caching mechanism
  • Can be integrated with Organic Groups
  • Integrates with Views

More here: https://www.drupal.org/node/2457747

Panels in use ⌘

  • Panel nodes
  • Panel Pages (with variants)
  • Panelized content types, with the option to panelize individual nodes

And much more: https://www.drupal.org/node/2457747

Panelizer vs Page Manager ⌘

Panelizer Page Manager
  • does mostly the same as core's Layout Builder
    • don't use them both at the same time (lots of overlapping code, etc)
  • allows to attach Panels to any node
  • provides a single entity type (a panel)
    • works for many entity types
    • with Page Manager template takes over the page rendering of the entity
  • supports the creation of new pages, allows placing blocks within page
  • provides "page variants", each with their own selection conditions
  • can be used to take over an existing page
    • i.e. overrides /node/% to change what is displayed (view node)
  • utilizes the core Conditions, Context, and Blocks APIs
  • will not include any Layout GUI

Display Suite ⌘

Yet another drug and drop display manager

  • Arranges nodes, views, comments, user data etc. the way we want
    • without having to work our way through dozens of template files
    • has a predefined list of layouts
  • Allows to define custom view modes

Display Suite con't ⌘

  • Exportables
  • own custom fields in the backend or in our code
  • custom layouts in our theme
  • Change labels, add styles or override field settings (semantic fields)
  • Full integration with Views and Panels
  • Powerful extension: Field Group module

Paragraphs ⌘

Add more editing power to end-users

Exercise 4.1. ⌘

  1. Layout Builder and Field Layout exercise
    1. Create your own content type (map something from your own business/company) - Course Outline
      • Add at least 2 custom fields - Duration(number-days), Requirements(text)
    2. For the whole content type and for each content item make it layout-able
    3. For the whole content type change the section layout into this 3colLayout.png
      • Place your fields - at least one in each sub-region
      • Create a node of this type
    4. For another node instance (create it's content first) change the section layout into this 2colLayout.png
      • Place your fields in a different way
    5. For the form display change the layout into "Two column bricks"
      • Place the fields, at least one in each sub-region

Exercise 4.2. ⌘

  1. Image Responsive exercise
    • Make image field in 'Article' responsive
  2. Panels and Panelizer/Page Manager exercise
    • Make custom panel page "Themers Guide"
      • Provide 2 variants - d7ver, d8ver
  3. Display Suite exercise
  4. Paragraphs exercise

Theme system ⌘

ThemeSystem.jpg


The theme system, which controls the output of Drupal.

(https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21theme.api.php/group/themeable/8.2.x)

Themable drupal elements (via theme function or template file):

(https://api.drupal.org/api/drupal/core%21includes%21theme.inc/8.2.x)

Theme system con't ⌘

  • Allows a theme to have huge control over the appearance of the site
    • markup and the CSS used to style the markup
  • Modules don't write HTML markup directly
  • They instead return "render arrays", structured hierarchical arrays which include
    • the data to be rendered into HTML (also XML or other formats)
    • and options that affect the markup
  • Those arrays are rendered by recursive calls to drupal_render()
    • Traverse the depth of the render array hierarchy
    • At each level, the theme system does the actual rendering

Theme engines ⌘

Drupal 8 uses Twig engine

Twig Template Engine ⌘

TwigEngine.jpg


Handles integration of PHP templates with the Drupal theme system.

(https://www.drupal.org/theme-guide/8/twig)

Twig - helping modules ⌘

Theme Hooks ⌘

Hook.png

Overriding Theme Hooks ⌘

Preprocessing for Template Files ⌘

  • render_example

Preprocessing for Theme Functions ⌘

Theme hook suggestions ⌘

Altering theme hook suggestions ⌘

Assets ⌘

Exercise 5 ⌘

  1. Change existing twig template
  2. Create our own twig template
  3. Preprocess for template file
  4. Preprocess for theme function
  5. Suggest with theme hook
  6. Create and manage some assets

Creating a new theme from scratch ⌘

ThemeFromScratch.jpg


Let's create 'Difficult Dirty' theme.

Steps ⌘

General steps:

  1. Create or modify an HTML file(s)
  2. Create or modify a CSS file(s)
  3. Create an '.info.yml' file
  4. Standardize the file names according to Drupal conventions
  5. Insert available variables into template
  6. Create additional files for individual node types, blocks, etc

File .info.yml ⌘

Example:

name: Theme Name
type: theme
description: A description for Theme.
core: 8.x
libraries:
  - themname/global-styling
stylesheets-remove:
  - '@classy/css/components/tabs.css'
  - core/assets/vendor/normalize-css/normalize.css
regions:
  header: Header
  content: Content  # the content region is required
  sidebar_first: 'Sidebar first'
  footer: Footer

Related theme settings docs:

(https://www.drupal.org/theme-guide/8/defining-a-theme)

Exercise 6 ⌘

Create theme 'Difficult Dirty' from scratch:

  • make dir here 'your_site/themes/custom/difficultdirty'
  • in newly created dir add file 'difficultdirty.info.yml' with following content and enable the theme and test the website:
name: Theme Name
type: theme
description: A description for Theme.
core: 8.x

CSS file ⌘

Exercise 7 ⌘

Prepare css file:

  • Recreate structure of
    • css files
    • related config/settings from .yml and .theme files

Structure of a Drupal Page ⌘

  • Hierarchical set of twig templates
    • Stark example
    • Bartik example

From Stark Theme ⌘

TwigCallGraphStark.png

From Bartik Theme ⌘

TwigCallGraphBartik.png


Devel Module(s), Other Helpers ⌘

DddThemes.jpg

Source: http://img.clipartlook.com

Drupal Devel Suite ⌘

  • Devel suite
    • Devel
    • Devel Generate
    • Devel Kint
    • Drupal Web Profiler
      • Assets, Blocks, Cache, Config, Database, Devel, Events,
      • Extensions, Forms, Http, Mail, PHP Config, Performance Timing, Request,
      • Routing, Services, State, Theme, Timeline, User, Views

Drupal Devel ⌘

  • Suite of modules that provides
    • helper functions, admin pages
    • additional development Drush commands to use during development (fn-hook, fn-event, ...)
  • Main uses
    • Inspecting Service Container (its Services and Parameters)
    • Inspecting Routes (routing data from .routing.yml's and from classes subscribing to route build/alter events)
    • Inspecting Events (listeners registered in the event dispatcher)
  • Devel api https://api.drupal.org/api/devel/8.x-1.x

Drupal Devel Generate ⌘

  • Bulk creates nodes, users, comment, terms for development
  • Has Drush integration

Devel Kint ⌘

Useful during development

  • Gives dpr() function - pretty prints variables
  • Similar helpers - dpm(), dvm()

Drupal Web Profiler ⌘

  • Adds a debug bar at bottom of all pages
    • a query list, cache hit/miss data, memory profiling, page speed, php info, session info, etc
    • we can collect the time needed to instantiate every single service used in a request
      • see ../README.md file for instructions

Theme registry ⌘

  • Variable which keeps all the theme related items
    • devel/theme/registry

Theme debug mode ⌘

  • Enable Twig Debugging in sites/default/services.yml
    • If the file doesn't yet exist, copy default.services.yml to services.yml
    • Set the debug variable to true, clear cache
parameters:
  twig.config:
    debug: true 
  • Inspect or view source

Popular Drupal 8 Themes ⌘

Drupal 8 Distributions ⌘

Drupal themes future? ⌘

DecoupledDrupal.png

Source: https://dri.es/how-to-decouple-drupal-in-2019