Skip to main content

When was the last time your website had a facelift or created a strategy to improve your brand visibility in versatile, exciting, and engaging ways? Revamping your website with interactive content and improved user experience delivers true value to your organization. Website redesigning with a contemporary design, modern trends and enhanced functionality improves your bottom line. 

Why not make invest your time and money in trusted and reliable CMS platform? With a better looking website and navigation experience, drive heavy traffic to your website and easily convert even casual visitors into customers. Even better, when you redesign your website’s content with the most modern content management system like Drupal 8 to take the pain out of your IT problems. 

Drupal is a free, open source software, produced by over a million users in 230 countries speaking 181 languages. Drupal is the best CMS platform for web content management among global enterprises, governments, higher education institutions, and NGOs. Drupal is highly flexible, secure and scalable to serve your technical and business requirements in Drupal 8 development. Drupal 8 offers powerful digital solutions and is backed by one of the world’s most innovative open source communities.

Here are ten important benefits of redesigning your website with Drupal 8 to meet your business goals:

1. Easy Content Authoring

Drupal is built with essential tools for content creation and publishing, like a customizable WYSIWYG editor to meet the unique requirements of authors, publishers and Drupal developers. Drupal offers role-based permissions for managing editorial workflows as well as content.

2. Responsive Design

According to a recent survey, consumers spend five hours on mobile devices every day. Thirty percent of Google searches are now being performed on some sort of mobile device. Drupal leverages responsive design technology to access content on-the-go from various screen sizes and devices such as iPhone, Android, and others.

3. Usability & User Experience

When an UX is developed well in a website, visitors will easily find the information they need without delay and frustration. Even though the quality of content, graphic design, and the reputation of a company is great, a website design that is not logical and orderly leads to a bad user experience.

4. Image Optimization

Images causes some sites to be painfully slow. Drupal 8 websites are amazing with beautiful images optimized for search engines and you can save on data as well.

5. Website Performance 
Optimizing the speed of the web pages by minimizing HTTP requests, minifying HTML, CSS and Javascript, caching, deferring parsing of javascripts, avoiding bad requests and using content delivery networks can just ensure a rewarding browsing experience.

6. Data Migration

If you're running into a lot of roadblocks when you try to update your current site, you have to redesign with a new CMS. Drupal 8 allows you to very easily import your database  including critical pages, images, or downloadable files 

7. Website Security

Drupal 8 is built with comprehensive security by default to safeguard website content and manage its accessibility. The important security features and improvements include HTML generation with Twig templates, cross site scripting, SQL injection, use of PHP as input format, improved content entry and filtering, route definitions, clickjacking protection, CSP support, and more

8. PHP 7 Compatibility

Drupal 8 is PHP 7-ready and sites that run many contrib modules, or particularly memory-intensive need increased memory requirements.  Drupal 8 performance optimization with PHP 7 maximizes the overall page speed and performance of the website.  

9. SEO-friendly CMS

Search engine optimization is an integral part of any website. Drupal 8 comes with out-of-the-box built-in SEO features to drive heavy traffic to the website and improve search engine rankings. Drupal 8 is optimized for SEO with increased site speed, responsive web design, mobile-readiness, content-as-a-service capabilities, clean URLs, advanced search, multilingual sitemap and more to increase the reach and visibility of your website.

10. Multilingual Website

Drupal publishes a single web site or shares content in multiple languages across multiple devices. Drupal 8 is configured with complete and powerful translation module with multiple language handling, interface translation, content translation, and configuration translation to deliver better experience than ever before and save incredible amount of time and money.

Drupal 8 is powered with improved features and functionality, and as the platform matures, it is poised to become the backbone of more and more digital experiences.

Drupal is PHP 7-ready and sites that run many contrib modules, or particularly memory-intensive ones, will need more memory requirements. Optimizing Drupal website performance with PHP 7 version will boost the overall page speed. 

PHP 7 was released in December 2015 and offers high performance, huge load capacity and asynchronous programming support  for online applications. According to the latest study, PHP 7 is twice as fast as PHP 5.6 and reduces memory usage.


Why this is the right time to move to PHP 7

Drupal 7 core officially supports PHP 5.2.5 or higher  However, PHP 7 introduces backward incompatible changes which may need to be addressed in contributed or custom modules and themes. While some Drupal 7 sites may run on minimum of PHP versions, you can move to Drupal 8 with PHP 7 support to enhance the performance of the site.

Drupal 8 officially supports 200+ new features and improved functionalities, and upgrading to PHP 7 brings a lot of improvements and delivers high performance Drupal site, whether you are a website owner or a Drupal developer

Drupal core's automated test suite is now fully passing on a variety of environments where there were previously some failures (PHP 5.4, 5.5, 5.6, and 7). Several bugs affecting those versions were fixed as well. These PHP versions are officially supported by Drupal 7 and recommended for use where possible.

Anecdotal evidence from a variety of users suggests that Drupal 7 can be successfully used on PHP 7, both before and after the 7.50 release. 

A slow website load time impacts visitors, overall user experience, and the bottom line. With the improved speed enhancements of Drupal 7 and Drupal 8 with PHP 7, your user engagement and experience will increase and less likely they will leave your website

In our earlier article, we had a solid understanding of Drupal 8 theming. In this post, we're going to dig into the theming fundamentals, files for styles, JS, CSS, library, Twig templates , adding new regions, attach the library to all the pages and working with breakpoints in Drupal 8 development.

Creating a Drupal 8 sub-theme

Sub-themes are just like any other theme, with one difference: they inherit the parent theme's resources. There are no limits on the chaining capabilities connecting sub-themes to their parents. A sub-theme can be a child of another sub-theme, and it can be branched and organized however you see fit. This is what gives sub-themes great potential.

To create a sub-theme you define your theme like any other theme and declare the base theme using the "base theme" key. Note that the key has no underscore.

Create an .info.yml file

To create a Drupal 8 theme you need to first create a file that provides meta-data about your theme to Drupal. This is similar to how modules and installation profiles are being defined, and as such it is important to set the 'type' key in the .info.yml file to 'theme' in order to differentiate it.

If your theme is named “Flower" then the folder is named “flower/" and the .info.yml file is named "flower/"

name: Flower
type: theme
description: 'A flower theme that offers extra fluffiness.'
package: Custom
core: 8.x
  - flower/globalstyling
  - '@classy/css/layout.css'
  - core/assets/vendor/normalize-css/normalize.css
  header: Header
  content: Content
  sidebar_first: 'Sidebar first'
  footer: Footer

Folder Structure

In Drupal 8, we can use the "themes" folder to add a new theme. You should note that Drupal core themes such as Bartik and Seven are located in the core/themes folder of your installation.

The best practice is to place the contributed themes in a sub folder named "contrib" and your own themes in a folder named "custom".

Here are some examples of files and folders that are structured in the new theme folder structure:

 |  |-install
 |  |  |-flower.settings.yml
 |  |-schema
 |  |  |-flower.schema.yml
 |  |-style.css
 |  |-flower.js
 |  |-buttons.png
 |  |-maintenance-page.html.twig
 |  |-node.html.twig

Twig in Drupal 8

Twig is a template engine for PHP and it is part of the Symfony2 framework. One of the results of this change is that all of the theme_* functions and PHPTemplate based *.tpl.php files have been replaced in by *.html.twig template files. Learn how to use the twig template engine in Drupal 8.

Adding Regions to a Theme

Adding region meta-data to your file
- Editing your page.html.twig file and printing the new regions

Declaring any new regions in your file. Regions are declared as children of the regions key like so:

# Regions
  header: 'Header'
  content: 'Content'
  footer: 'Footer'


header: 'Header'
Will become:

{{ page.header }}

In your Twig templates.

Adding (CSS) and JavaScript (JS) to a Drupal 8 theme

In Drupal 8, stylesheets (CSS) and JavaScript (JS) are loaded through the same system for modules (code) and themes.

Defining a library

To define one or more (asset) libraries, add a *.libraries.yml file to your theme folder. (If your theme is named fluffiness, then the file name should be fluffiness.libraries.yml). Each "library" in the file is an entry detailing CSS and JS files (assets)

Defining JS files

  version: 1.x
      css/cuddly-slider.css: {}
    js/cuddly-slider.js: {}
    - core/jquery

Defining CSS file

Defining CSS file
  version: 1.x
      css/layout.css: {}
      css/style.css: {}
      css/colors.css: {}
      css/print.css: { media: print }

Attaching a library file

  • Attaching a library to All page(s)

    To attach a library to all the pages on the site that use your theme, declare it in your theme's *.info.yml file, under the libraries key:

    name: Flower
    type: theme
    core: 8.x
      - flower/cuddly-slider

    You can list as many libraries as you want, all of them will be loaded on every page.

  • Attaching a library to a subset of pages :

    A theme can make this happen by implementing a THEME_preprocess_HOOK() function in the .theme file, replacing "THEME" with the machine name of your theme and "HOOK" by the machine name of the theme hook.

    For instance, if you want to attach JavaScript to the maintenance page, the "HOOK" part is "maintenance_page", and your function would look like this:

        function flower_preprocess_maintenance_page(&$variables) {
           $variables['#attached']['library'][] = 'flower/cuddly-slider';

Including Default Image Styles With Your Theme

The process for including an image style in your theme is similar to that of including default configuration in a module.

  • Create the Image Style you wish to include using the UI
  • Export the Image Style as YAML
  • Include the exported YAML in the config/install directory of your theme following the appropriate naming convention.
  • Start by creating an image style using the admin UI at Configuration > Image Styles (admin/config/media/image-styles). Once the image style has been created and saved, the configuration that makes up that image style will be stored in your site's active config.

This configuration can be exported using:

  • Single import/export tool at Configuration > Configuration management > Single Import/Export > Export (admin/config/development/configuration/single/export).
  • From the configuration type select list choose "Image style" then choose your image style from the configuration name select list.

Example: flower/config/install/

langcode: en
status: true
dependencies: {  }
name: black_white
label: 'black & white'
    uuid: 8d4f85cc-9a2d-4a30-af15-21b0833dc06d
    id: image_desaturate
    weight: 1
    data: {  }
third_party_settings: {  }

Working with breakpoints in Drupal 8

Breakpoint's properties

  • label - A human readable label for the breakpoint.
  • mediaQuery - Media query text proper all and (min-width: 851px).
  • weight - Positional weight (order) for the breakpoint.
  • multipliers - Supported pixel resolution multipliers.

Example: flower.breakpoints.yml
label: mobile
mediaQuery: ''
weight: 2
    - 1x
  label: narrow
  mediaQuery: 'all and (min-width: 560px) and (max-width: 850px)'
  weight: 1
    - 1x
  label: wide
  mediaQuery: 'all and (min-width: 851px)'
  weight: 0
    - 1x

I hope this Drupal 8 theming guide illuminates the fundamentals of getting a theme started so that you can use it for Drupal projects.

Most of the organizations are increasingly implementing web based mapping systems, this is where the importance of mapping to Drupal comes in.  Drupal 8 development offers amazing tools for mapping. It integrates with a lot of libraries, technologies and third party services. There are solutions for simple maps but also for complex mapping needs.

If you start mapping with Drupal, you need to use a combination of location modules to achieve your goal.

There are currently stable modules in Drupal that enable gathering, storage, processing and display of geospatial data;

Setting up Drupal Mapping

  • Coordinate systems (the center of the earth, the plane of origin of latitude, & the plane of origin of longitude) 
  • Models of Earth (EPSG codes) 
  • Specifying a location (latitude, longitude, & height above a surface model) 
  • Map projections (flattening the Earth) 5
  • Location data (latitude & longitude) are special
  • They are not your typical data format: text/number/dates
  • Since you usually want to measure distances and areas, which are sensitive to coordinate systems & projections, they must be special objects to be efficiently handled by spatial functions
  • Also, we often want our points, lines, polygons to be easy to customize/style, we must create new data type format for this mechanism to be possible

Applying geospatial data storage in Drupal CMS

  • KML, GPX, and GeoJSON are usually text file formats
  • WKT is usually implemented as a database object format, hence faster or more efficient to process. 
  • Keyhole Markup Language - XML variant, popularized by Google, default format in Google Earth 
  • GPS eXchange Format - XML schema designed for GPS data format, Native format in GPS-capable smartphones/devices 
  • GeoJSON -  JSON object ,  generally more compact than KML/GPX 
  • Well-Known Text - text markup language for representing vector geometry objects

Drupal is a powerful Open Source CMS which has a large community of Drupal developers, designers and users. Drupal mapping continue to increase as more people become aware of the numerous benefits maps and GIS applications provide. The future is bright for a comprehensive Drupal mapping system that combines all the best geospatial modules.

People are familiar with a Drupal theme and one of the first thing any Drupal developer need to understand how to apply the new tools and techniques to build a Drupal theme from scratch.

Getting started with a Drupal theme

  • Themes allow you to change the look and feel of your Drupal site 
  • Use contributed themes or create a new theme from scratch and share with the community
  • Create a sub-theme of an existing theme. A sub-theme inherits a parent theme's resources

Do more with a Drupal theme

  • Change layouts, regions, images and fonts
  • Hide or display fields dependent on user role
  • Dynamically respond to changes in the content, or to user input
  • Modify or replace text (e.g., labels or attributes) and variables generated by modules
  • Convert any website layout or template into a Drupal theme

Drupal 8 Theming

  • Defining a theme with an .info.yml file
  • Theme folder structure
  • Twig in Drupal 8
  • Adding Regions to a theme
  • Adding stylesheets (CSS) and JavaScript (JS) 
  • Creating a Drupal 8 sub-theme
  • Include default image styles with your theme
  • Use attributes in templates
  • Working with breakpoints in Drupal 8

Theming differences between Drupal 6, 7 & 8

Here are the most noteworthy changes in Drupal 8 that affect theming:

  • Drupal 8 outputs semantic HTML5 markup by default (see Drupal 8 HTML5 Initiative), compared to XHTML in Drupal 6 and 7.
  • Besides jQuery v2.x Drupal 8 now includes more front-end libraries such as  Modernizr, Underscore.js and Backbone.js.
  • Drupal 8's core RDFa  module outputs markup
  • outputs markup
  • Drupal 8 has improved accessibility making extensive use of WAI-ARIA attributes.
  • Drupal 8 introduces Twig, which replaces PHPTemplate as the default theme engine. This means the theme_* functions and PHP-based *.tpl.php files have been replaced by *.html.twig templates ()
  • Drupal 8 enables by default features that improve performance such as CSS and JavaScript aggregation.
  • Drupal 8 ships with new UI elements that you use in your own admin screens, including modal dialogs and drop buttons
  • Drupal 8 ships with responsive features such as responsive themes, toolbar, images, and tables
  • In Drupal 6 and 7 if you wanted to add CSS or JS to a particular page, you'd use the drupal_add_css() and drupal_add_js() functions, respectively. This is now replaced byinsert any JS/CSS assets in the #attached property of a render array
  • Drupal 8 drops support for IE 6, 7 and 8, enabling the use of jQuery 2.0 and other code that assumes modern HTML5/CSS3 browser support.
  • Drupal 8 does not support browsers that do not support SVG (including IE8 and Android Browser 2.3)
  • Drupal 8 contains less IDs than Drupal 7's CSS
  • Drupal 8's CSS (file) structure is based on SMACSS & BEM
  • Drupal 8's CSS uses CSS3 pseudo selectors
  • Drupal 8 ships with Classy, a core base theme that injects classes into markup, and includes corresponding CSS. In progress: This will replace many pre-process functions and CSS files which were previously included in core modules
  • Drupal 8 moves CSS classes from pre-process functions to Twig templates
  • Drupal 8 uses breakpoint media queries to control how the site looks on different devices

After you have grasped some basic ideas about your template folder, its files, and the layout of your theme, let's move on to create a Drupal 8 theme in future posts in this series. Join the conversation by commenting below with any questions or feedback on using Drupal 8 theme for your project.

Drupal 8 Form API is similar to Drupal 7 form API. The forms are still represented with nested array structure as Drupal 7 to render the data. However, there is a separate validation and submission form as well.

Form Generation

  • There are different classes, functions and interfaces to choose depending on the type of form you are creating.
  • Drupal 8 has some new HTML 5 elements (telephone, email, date) to render array structure.
  • The basic workflow of a form is defined by buildForm, validateForm, and submitForm methods of the interface.

Create a Directory Structure

Create a directory within a new custom module. 


Create your formExample.module in below directory structure


Form ID

This needs to return a string that is the unique ID of your form. Namespace the form ID based on your module's name.


Drupal 8

public function getFormId() {
       return 'multistep_form_one';

Drupal 7

function multistep_form_one($form,$form_state) {



This needs to returns a Form API array that defines each of the elements your form is composed of.


public function bulidForm(array $form, FormStateInterface $form_state) {
       $form[‘name’] = array(
            ‘#type’ => ‘textfield’,
            ‘title’=> ‘name’,
       return $form;



public function validateForm(array $form, FormStateInterface $form_state) {
           $form_state->setErrorByName(“Enter only alphabets”);



public function submitForm(array &$form, FormStateInterface $form_state) {
    foreach ($form_state->getValues() as $key => $value) {
      drupal_set_message($key . ': ' . $value);


We are done with creating custom form elements, fields, field formatters, etc. in Drupal 8. Our expert Drupal developers will be covering session data storage with Drupal 8 in future posts in this series. Join the conversation by commenting below with any questions or feedback on using these Drupal 8 constructs.

Hooks are PHP functions that are created for each module when system events happen, e.g. page load or user login.
In Drupal 7 custom pages are created using hook_menu. Drupal 8 is yaml-based and you need create controller, routes.yml and basic info file for your module.

Comparison of hooks in Drupal 7 & Drupal 8 

  • Number of hooks in Drupal 7:  352
  • Number of hooks in Drupal 8:  338
  • Deprecated hooks: 83 
  • New hooks in Drupal 8: 56
  • Renamed hooks: at least 4

Examples of deprecated hooks


 hook_menu() -> Drupal 8 APIs should start with defining the routes for the items.    

    # Drupal 7 menu item
    $items['admin/content/book'] = array(
    'title' => 'Books',
    'description' => "Manage your site's book outlines.",
    'page callback' => 'book_admin_overview',
    'access arguments' => array('administer book outlines'),
    'type' => MENU_LOCAL_TASK,
    'file' => '',


# Drupal 8 book.routing.yml snippet
  path: '/admin/content/book'
    _controller: ‘\Drupalbook\Controller\BookController::adminOverview'
    _title: 'Books'
    _permission: 'administer book outlines‘
     # Drupal 8 book.links.task.yml snippet
  route_name: book.admin
  title: 'Books'
  base_route: system.admin_content

hook_init() -> Drupal 8 has adopted symfony as a part of its core. It uses Symfony kernel and events to do the same now.

function mymodule_init() {
  if (!empty($_GET['redirect-me'])) {

If your module just needs to add css and/or javascript, hook_page_attachments should be used in.

function MYMODULE_page_attachments(array &$attachments) { 
  $attachments ['#attached']['library'][] = 'modulename/libraryname'; 


hook_block_configure , hook_block_info, hook_block_view -> A "plugin" is just a new way of creating reusable elements in Drupal. Blocks are now created with plugins. 

 * Provides a 'Hello' Block
 * @Block(
 *   id = "hello_block",
 *   admin_label = @Translation("Hello block"),
 * )

namespace Drupal\hello_world\Plugin\Block;
use Drupal\Core\Block\BlockBase;
class HelloBlock extends BlockBase {
   * {@inheritdoc}
  public function build() {
    return array(
      '#markup' => $this->t('Hello, World!'),

Creating a hook

As a Drupal Developer the easiest way to implement a hook is to copy the example from the .api.php file into your module, then rename the function by replacing the starting 'HOOK' with the name of your module. For example, if your module is named 'mymodule' and you're using a form_alter, hook_form_alter becomes mymodule_form_alter.

Then write the desired functionality, returning output how the hook requires. Hook return values might be set in passed parameters rather than a return statement in the function.

Drupal 8 is one of the most widely used Content Management System to publish content easily. Drupal  is an open source website development platform. Drupal 8 is used to build websites, from easy to complex, that fits your budget and skill level. Symfony is an open source MVC framework for PHP that powers a lot of websites and it plays a major role with the launch of Drupal 8. Here are some important merits of using Drupal 8.


  • Responsive design

Drupal 8 comes with more robust new configuration management system and is compatible with mobile devices and thus it overcomes the limitations of Drupal 7 with regard to mobile devices.

  • Improved semantics with HTML5

Drupal 8 pages are HTML5-based and thus each output template has simplified elements and classes with native input tools for mobile fields like date, email and phone.HTML5 is also used for better markup.

  • Symfony Framework

Drupal 8 uses Symfony and this opens access to a large set of external libraries while was improves the PHP syntax of Drupal.

  • Module Readiness

Many Drupal 7 contributed modules are now in Drupal 8 core itself like views module (In Drupal 7 views module is in contributed module list but in Drupal 8 it is in core).So there is no need to install those modules in Drupal 8.

  • Twig Template

Drupal 8 includes the flexible, fast, and secure template engine for PHP called Twig. With Twig, templates are now written an easy-to-learn syntax which brings several simplifications and greater security.

  • Low Cost

Building a website with Drupal 8 is less expensive than using any of its earlier versions, also because eventually you will need to upgrade it to Drupal 8 in a short span of time.

  • Quick Edit

Quick edit tool is one of the advantage in Drupal 8.We can easily edit text directly from the front-end of your site.

  • Multi-language support

Drupal 8 has built-in multilingual feature and thus you can easily translate anything in the system using built-in user interface. Drupal is great for building multilingual websites and this feature will benefit both end users and the Drupal developer to reach greater audiences on both sides.

With merits we have some demerits as well. Here are the Drupal 8 demerits…


  • Symfony

Drupal 8 uses Symfony and this means the developers have to retrain themselves to adjust to the changes.

  • Drupal 8 Migration

There is no continuity/upgrade path from Drupal 7 to Drupal 8 . So the sites have to be rebuilt completely.

  • Contributed Modules

Drupal 8 Contributed modules are less when compared to Drupal 7. All the existing Drupal modules have to be upgraded to work on Drupal 8.

Drupal 8 is highly scalable, flexible and customizable that makes Drupal the open source CMS platform that more and more companies, small, medium and large enterprises, are adopting because of the features and functionality it offers them, but also its easy to maintain and less likely to break down over time.

Drupal developers can create custom pages using custom templates and routing in Drupal 8. Follow Drupal coding standards. Keep modules in root directory as given below.


In custom folder contains our own custom modules. In contrib folder contains Drupal contributed modules.

Custom Module


Create a custom module

Module name: example


Drupal 7 - ( to store metadata about the module.
Drupal 8 - ( to store metadata about the module.

Path: modules/custom/example/


name: Example Custom Module
description: 'Provides a custom functionality' 
type: module 
core: 8.x 
package: Custom


Drupal 7 - Have hook_menu() to declare the path.
Drupal 8 - Create the routing.yml file.

The path of the content will be defined in example.routing.yml

Path: modules/custom/example/example.routing.yml


  path: '/icecream/list'
    _controller: '\Drupal\example\Controller\IcecreamController::icecreamPage'
    _title: 'My Custom Icecream Page'
    _permission: 'access content'

Explanation about Routing code

example.icecream_page - machine name of the route
path - It gives the path to the page on the site. Note the leading slash (/)
defaults - It describes the page and title callbacks
  IcecreamController: Controller class name and it should be the file name of controller
    icecreamPage: Method Name
requirements - It is a condition to be displayed under the particular page. Can specify modules, permissions that must be enabled.

Page implementation


Drupal 7 - Have .inc or .module file to define the method.
Drupal 8 - Create the Icecreamcontroller.php file.

The path of the content will be defined in Icecreamcontroller.php

Path: modules/custom/example/src/Controller/IcecreamController.php


 * @file
 * @author Anitha
 * Contains \Drupal\example\Controller\IcecreamController.

namespace Drupal\example\Controller;

use Drupal\Core\Controller\ControllerBase;

 * Provides route responses for the example module.
class IcecreamController extends ControllerBase {

   * Returns a simple page.
   * @return array
   *   A simple renderable array.
  public function icecreamPage() {
    $element = array(
      '#markup' => 'Frame all your needed contents',
    return $element;


After clearing the cache and see your custom page.

Features, Functions & Benefits

  • Can easily attach a theming function i.e  and/or tpl.php to a URL path/pattern.
  • Integration with the Context module Note : use custompage_region_tile($region_name) to include regions in custom pages, but not template variables!
  • Better for SEO and other presentations
  • To do package both data collection functions and an initial theme in a module
  • User-interface enhancement that will allow inline editing of the aggregated content items such as nodes and views on a custom page itself
  • Can do Custom Page to include a node with nid in site's default language and will know to swap it with the translation node when language is switched.

What is Twig?

Twig is a faster, and more secure template system than PHP. Twig is brought by a wider PHP world. Twig was built  by SensioLabs, the creator of Symfony2 framework. Drupal 8 is using Symfony2 to overhaul its codebase. Twig was the right choice to use for Drupal themes.

Using Twig in Drupal

Twig is the default templating engine in Drupal 8.

One of the results of this change is that all of the theme_* functions and PHPTemplate based *.tpl.php files have been replaced in by *.html.twig template files.

Comparison of PHP template & Twig theming

1. Docblock

PHP Template

 * @file
 * File description


 * @file
 * File description

File Names

PHP Template file : node--article.tpl.php
Twig file : node--article.html.twig
PHP Template function : page.tpl.php
Twig file : page.html.twig


You can use a dot (.) to access attributes of a variable (methods or properties of a PHP object, or items of a PHP array), or the so-called "subscript" syntax ([]):

{{ }}
{{ user['name'] }}

Printing a variable

PHP Template

<div class="content"><?php print $user; ?></div>


<div class="content">{{ user }}</div>

Printing a hash key item

PHP Template

<?php print $user['#item']['alt']; ?>


{{ user['#item'].alt }}

Assigning a variable

PHP Template

<?php $new_var = $content->comments; ?>


{% set new_var = content.comments %}

Assigning an array

PHP Template

<?php $arguments = array('!author' => $author, '!date' => $created); ?>


{% set arguments = {'!author': author, '!date': created} %}

Setting Variables

You can assign values to variables inside code blocks.

{% set user = 'ram' %}
{% set num = [1, 2] %}
{% set ral = {'foo': 'bar'} %}



<?php if ($content->comments): endif; ?>


{% if content.comments %} {% endif %}


<?php if (!empty($content->comments)): endif; ?>


{% if content.comments is not empty %} {% endif %}


<?php if (isset($content->comments)): endif; ?>


{% if content.comments is defined %} {% endif %}


<?php if ($count > 0): endif; ?>


{% if count > 0 %} {% endif %}



PHP Template

<?php print check_plain($name); ?>


{{ name|striptags }}


PHP Template

<?php print t('Navigate'); ?>


{{ 'Navigate'|t }}

Implode a list

PHP Template

<?php echo implode(', ', $regions); ?>

Original Twig:

{{ regions | join(', ') }}

Drupal 8 Twig:

{{ regions }}

How to enable debugging?

  1. Locate your site's services.yml file, likely located in sites/default/services.yml
  2. Edit the services.yml file and enable one or more of the debugging options defined below.


    debug: true


The dump function dumps information about a template variable. This is mostly useful to debug a template that does not behave as expected by introspecting its variables:

{{ dump(user) }}

In an HTML context, wrap the output with a pre tag to make it easier to read:

{{ dump(user) }}


Determine whether a variable is empty:

{# evaluates to true if the user variable is null, false, an empty array, or the empty string #}

{% if user is empty %}
{% endif %}

Advantage of using Twig

Concise: The PHP language is verbose and becomes ridiculously verbose when it comes to output escaping:

<?php echo $variable ?>
<?php echo htmlspecialchars($variable, ENT_QUOTES, 'UTF-8') ?>
{{ variable }}
{{ variable|escape }}
{{ variable|e }}         {# shortcut to escape a variable #}

Template oriented syntax

Twig has shortcuts for common patterns, like having a default text displayed when you iterate over an empty array:

{% for region in regions %}
    * {{ }}
{% else %}
    No regions have been found.
{% endfor %}

Full featured

Twig supports everything you need to build powerful templates with ease such as multiple inheritance, blocks, automatic output-escaping, and much more:

{% extends "sample.html" %}
{% block content %}
    Content of the page...
{% endblock %}


Functions can be called to generate content. Functions are called by their name followed by parentheses (()) and may have arguments.

For instance, the range function returns a list containing an arithmetic progression of integers:

{% for i in range(0, 3) %}
    {{ i }},
{% endfor %}

Twig: Fast Template

Using Twig will accelerate the performance in Drupal 8. In order to achieve the best speed possible and save time during Drupal development, Twig compiles templates down to plain optimized PHP code.

The overhead compared to regular PHP code was reduced to the very minimum.

A control structure refers to all those things that control the flow of a program - conditionals (i.e. if/elseif/else), for-loops, as well as things like blocks. Control structures appear inside {% ... %} blocks.

For example, to display a list of users provided in a variable called users, use the following tag:


    {% for region in regions %}
        <li>{{|e }}</li>
    {% endfor %}


The if tag can be used to test an expression:

{% if regions|length > 0 %}
        {% for region in regions %}
            <li>{{|e }}</li>
        {% endfor %}
{% endif %}


To comment-out part of a line in a template, use the comment syntax {# ... #}. This is useful for debugging or to add information for other template designers or yourself:

{# note: disabled template because we no longer use this
    {% for region in regions %}
    {% endfor %}


Subscribe to Drupal 8

start with anubavam today

You have an idea we have engineers to convert your ideas into reality

Request Quote