Skip to main content

A web service is a software system designed to support interoperable machine-to-machine interaction over a network. Web services is a well-defined way for two computers to communicate with each other over the internet. 

Drupal web services is always a good option for you

In Drupal, web service is being used to communicate with other web applications or mobile applications. Content can be shared and easily integrated with other applications as well. 

Why use web services in Drupal?

Web services are useful because they present us with an architecture where a resource on a site (an image, textual content, such as a node ID or block ID, a video or audio file) is given a unique identifier. 

Use cases 

For example, in Drupal, every node has an ID. Every file you upload to a Drupal site also has a unique path to it.

This is extremely useful since all applications share this common semantic standard. We name things similarly on all of our web applications. 

Drupal services and real world examples

Here are some examples, perhaps we have to build a product site and they are developing a app for that product site in mobile, then we can pass data from web to mobile app using the web service.  For example if the HR Department wants to integrate its job postings and applications with another web application such as job portals, web services can make this happen.

Advantages of Drupal web development services you can’t ignore

This leads to another advantage of using web services with Drupal and why we would choose to use Drupal in the first place. Instead of having to upload our photos twice—once to our Drupal site and then repeating the procedure to our some other applications, services allows us to upload the images to our Drupal site once and then automatically send that data over to other application which wants without having to upload one (or even a batch of images) again. It saves us time and speeds up the entire process of generating web-based content.

Building web services for Drupal 7

Drupal can use web services following any of the protocols mentioned earlier, including XML-RPC, REST, and SOAP. Drupal can consume web services by requesting data from other web applications using RSS and XML-formatted requests. As a Drupal developer, you can write your own service code in Drupal using PHP. You can also use the Services module as well as other service-specific contributed modules to create these web service requests.

Service module supports multiple interfaces like REST, XMLRPC, JSON, JSON-RPC, SOAP, AMF and more.

Make use of Drupal Services module for:

  • Integration with core Drupal functionality like files, nodes, taxonomy, users, files and more.
  • Response format API allows you to define response Formats for CONTENT-TYPE ie. application/json or application/xml. (also calls such as ENDPOINT/node/1.json work)

Additionally, all the communication between services, in our example between a client and a server, happens over HTTP (the standard web protocol). This is a uniform protocol that is used for transport and communication of the service. All transports take place uniformly using GET, POST, PUT, and DELETE requests, for example.

The HTTP requests are stand alone and occurs at one given moment and is isolated from all other activated requests. If HTTP requests works and gets a response, it succeeds. If HTTP requests doesn’t get response from the server or application it's communicating with, it fails. The requests can be repeated an infinite number of times.
 

A dependency is an object that can be used (a service). An injection is the passing of a dependency to a dependent object (a client) that would use it. The service is made part of the client's state. Passing the service to the client, rather than allowing a client to build or find the service, is the fundamental requirement of the pattern." Dependency injection is an advanced software design pattern and applying it will increase flexibility. Once you wrap your head around this pattern, you will be unstoppable.

A practical example of accessing services in objects using dependency injection

For the following example, let's assume we are creating a method that will use the service of A, we need to pull the dependencies of B and C into the plugin which we can use to inject whichever services we require.

  • Application needs A so:
  • Application gets A from the Container, so:
  • Container creates C
  • Container creates B and gives it C
  • Container creates A and gives it B
  • Application calls A
  • A calls B
  • B does something

Types of Dependency Injection

There are different types of Dependency Injection:

  • Constructor injection
  • Method injection
  • Setter and property injection
  • PHP callable injection

Constructor Injection

The DI container supports constructor injection with the help of type hints(Type hinting we can specify the expected data type) for constructor parameters. The type hints tell the container which classes or interfaces are dependent when it is used to create a new object. The container will try to get the instances of the dependent classes or interfaces and then inject them into the new object through the constructor.

Method Injection 

In constructor injection we saw that the dependent class will use the same concrete class for its entire lifetime. Now if we need to pass separate concrete class on each invocation of the method, we have to pass the dependency in the method only.

Setter & Property Injection

Now we have discussed two scenarios where in constructor injection we knew that the dependent class will use one concrete class for the entire lifetime. The second approach is to use the method injection where we can pass the concrete class object in the action method itself. But what if the responsibility of selection of concrete class and invocation of method are in separate places. In such cases we need property injection.

PHP Callable Injection

Container will use a registered PHP callable to build new instances of a class. Each time when yii\di\Container::get() is called, the corresponding callable will be invoked. The callable is responsible to resolve the dependencies and inject them appropriately to the newly created objects

Dependency Injection: Advantages & Disadvantages

Advantages

Reducing the dependency to each other of objects in application.
Unit testing is made easier.
Loosely couple 
Promotes re-usability of code or objects in different applications
Promotes logical abstraction of components.

Disadvantages

DI increases complexity, usually by increasing the number of classes since responsibilities are separated more, which is not always beneficial.
Code will be coupled to the dependency injection framework.
It takes time to learn
If misunderstood it can lead to more harm than good

Summary

Dependency injection is a very simple concept of decoupling your code and easier to read. By injecting dependencies to objects we can isolate their purpose and easily swap them with others. 

The service container is basically there to manage some classes. It keeps track of what a certain service needs before getting instantiated, does it for you and all you have to do is access the container to request that service. Using it the right way will save time and frustration, while Drupal developers will even make it easier for the layman. 

 

Learn about the Drupal community coding standards and best practices that every Drupal developer should care whenever writing the code for Drupal. If you are truly committed to Drupal, then you should guarantee the code you contribute back be standards compliant. Here are ten of the best practices for implementing Drupal coding standards:

1. Spacing and Tabbing

  • Use double space (not tab, yes both are different) for indentation 
  • Often, the IDE/Editor that we use for Drupal development aggravates this issue as most of the IDE is configured to use tab for every line-break.
  • Press <ENTER> ensure that it aligns the cursor to the same indent as previous line with tabbing that caused this indentation issue.

2. Code comments

  • Check this link below for Drupal comment standards (https://www.drupal.org/node/1354). Comments are generally defined and used to state what the following line of code or block of code is doing and why we are writing the logic that way if it needs explanation for any future Drupal developer.
  • Three types of comments can be used in Drupal, Single line commenting (starts with //), Multi-line commenting (starts with /*) and Doxygen commenting (starts with /**).
  • Single line commenting and Doxygen commenting has a wide following in Drupal. Even for the comments with more than a line, it is handled with repeat use of single line commenting. The following example shows the usage pattern:

         // The first line of the comment goes here.
        // Some other comment here.
        // Some more comments here.
        // This saves the $node object and creates/updates the node
           node_save($node);

  • Comments are strictly not to be used to invalidate the code, which means you can’t use the comments to comment-out some set of code that you think are not needed. 
  • If you think some block of code is not really needed, just remove them instead of commenting-it-out. 
  • Sometimes you might find, the block of code that may be needed in future but not needed right now. In such instances, you can invalidate the code by placing those unwanted code in the condition like mentioned below.

         if (0) {
         // Some big logic goes here
        // that are not needed in this release for production
        }

  • The above code gets invalidated, that is will not be executed ever as the condition "if (0)" always returns "FALSE", So the block of code inside that condition will not be executed.

3. Naming the function and variables

  • PHP was just procedural at the time of initial Drupal release. So all the coding standard in Drupal follows as such. That means all the function and variables should follow snake  case structure (as of Drupal7), which means variable names should start with small-letter words and underscore should be used to connect the words if the variable is going to contain multiple words. ($snake_case)
  • With the release of Drupal 8, the naming of variables and functions can also be used using camelCase structure, which means variable names should start with small-letter words with uppercase initials for the connective words in case of multi-word variable. (Eg. $camelCase)
  • In either way, we need to follow only one case throughout the file.
  • What we forget is, we mix cases (camelCase and snake_case) sometimes. This should be avoided. Sometimes we define functions without grouping of the function name. In Drupal, all the functions inside a module should be prefixed with the module name, which is called grouping of the function. This helps in avoiding the name conflicts between modules.

4. Uppercase variables

  • According to Drupal coding standard, UPPERCASE variables are considered as constants whether it's PHP constants (TRUE, FALSE, NULL) or Drupal constants (Eg: LANGUAGE_NONE).
  • Sometimes in order to stress the importance of variables, we name the variables in uppercase. This should be avoided.

5. Operator and logical statements

  •  We often forget to leave a space before and after the usage of operator (Eg. if(arg(0)=='node')). According to the Drupal coding standards, all the operators should have single space before and after the operator (Eg. if (arg(0) == 'node')).
  •  Use single space before the start curly braces. The opening curly should be on the same line as the opening statement, guided by single space. The closing curly brace should be on the end of the block and indented to the same level as the opening statement.

6. Line length and Wrapping

  • In general, all lines of code should be no longer than 80 characters. However, there are exceptions to the character limit for the variable and function name that are quite longer when correctly indented.
  • We often wrap the condition of the control statement for readability. Drupal coding standard encourages us to split the multiple conditions and evaluate each complex conditions into a variable and use that in the control statement for better readability.

7. Module placement

As far as Drupal 7 is considered, all the contributed modules should be grouped under the directory called "contrib" in "/sites/all/modules", whereas the custom modules should go inside "/sites/all/modules/custom". In Drupal 8, the same can be followed or utilize the "/module" directory and use the same grouping of the  modules.

8. Writing Javascript

  • Always use Drupal behavior for your custom scripts which runs every time there is change in DOM elements unlike the traditional jQuery.ready which runs only once during the page execution when the DOM elements are ready.

9. Placeholders for translate function t()

  • Use the placeholders for dynamic strings used inside t() function.
  • Generally t() function is used to translate the given strings, sometimes we might use the dynamic strings inside t() function by concatenating the values, which is the not the best practice formulated by Drupal.

     Example:

  • return t('@username, welcome to my website', array('@username' => $account->name));

10. Module file

  • Use the module file only for Drupal hooks and some commonly used custom functions that you need frequently. 
  • Use .inc file to define menu callbacks and other helper functions that are not needed to be defined in module file.

If we all code to standards, Drupal will be a stronger, more performant, more secure platform. Drupal will continue to grow and strengthen it’s community due to the quality of it’s codebase. Anubavam has been building Drupal sites and providing services such as Drupal 8 upgrade and migration services, Drupal E-commerce development services, and more. Anubavam is participating in Drupal core development since 2006 and has delivered 250+ projects to 100+ happy clients in 22 countries worldwide.

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 THEMENAME.info.yml 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/flower.info.yml"

name: Flower
type: theme
description: 'A flower theme that offers extra fluffiness.'
package: Custom
core: 8.x
libraries:
  - flower/globalstyling
stylesheets-remove:
  - '@classy/css/layout.css'
  - core/assets/vendor/normalize-css/normalize.css
regions:
  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:

 |-flower.breakpoints.yml
 |-flower.info.yml
 |-flower.libraries.yml
 |-flower.theme
 |-config
 |  |-install
 |  |  |-flower.settings.yml
 |  |-schema
 |  |  |-flower.schema.yml
 |-css
 |  |-style.css
 |-js
 |  |-flower.js
 |-images
 |  |-buttons.png
 |-logo.png
 |-screenshot.png
 |-templates
 |  |-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 flower.info.yml file
- Editing your page.html.twig file and printing the new regions

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

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

Example:

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

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

Defining CSS file

Defining CSS file
  global-styling:
  version: 1.x
  css:
    theme:
      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
    libraries:
      - 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:

    <?php
        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/image.style.black_white.yml

langcode: en
status: true
dependencies: {  }
name: black_white
label: 'black & white'
effects:
  8d4f85cc-9a2d-4a30-af15-21b0833dc06d:
    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

flower.mobile:
label: mobile
mediaQuery: ''
weight: 2
multipliers:
    - 1x
flower.narrow:
  label: narrow
  mediaQuery: 'all and (min-width: 560px) and (max-width: 850px)'
  weight: 1
  multipliers:
    - 1x
flower.wide:
  label: wide
  mediaQuery: 'all and (min-width: 851px)'
  weight: 0
  multipliers:
    - 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.

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

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

<?php
    # 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' => 'book.admin.inc',
  );
?>

 

# Drupal 8 book.routing.yml snippet
book.admin:
  path: '/admin/content/book'
defaults:
    _controller: ‘\Drupalbook\Controller\BookController::adminOverview'
    _title: 'Books'
requirements:
    _permission: 'administer book outlines‘
     # Drupal 8 book.links.task.yml snippet
book.admin:
  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.

<?php
function mymodule_init() {
  if (!empty($_GET['redirect-me'])) {
     drupal_goto('http://example.com/');
  }
}
?>

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

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. 
modules/yourmodule/src/Plugin/Block/YourBlockName.php

<?php
/**
 * 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 is powered by best-of-the-breed technologies which makes Drupal highly customizable and scalable. Drupal is free and open source and supported by an active community of over 1.3 million members from 100,000+ contributing users resulting in more than 37,000+ free plug-in and modules as well as themes which extends its core capabilities. 

Drupal 8 provides built-in security by default and simply bug-free modules aren’t enough to address the security challenges. When your site comes under fire from hackers and spambots, you always need an extra layer of security modules that provide your website better protection against exploitable vulnerabilities.

To that end, we have compiled top rated six essential Drupal modules to better protect your website from security vulnerabilities and other risky elements. This will create a strong security layer around your website, and help Drupal developer keep all sorts of Drupal security issues at bay.

1. Password Policy

The Password Policy module is configured with pre-defined parameters for creating secure passwords after ensuring that certain conditions are validated. With a little quick and easy setting of constraints, this security module can keep that door bolted shut from vulnerabilities.

2. TwoFactor Authentification

This module is increasingly used by site administrators to provide an extra layer of security for accessing your Drupal website by using two-factor authentication with onetime password/PINs delivered on your mobile devices. When the pre-generated codes are successfully entered, access is granted to users. This mechanism protects the user account from attackers.

3. Automated Logouts

This module enables site administrators to create a policy of logging out users after a specified period of inactivity. It is highly customizable by role-based permissions to enforce different timeouts. It can be Automated Logout can be easily integrated with Javascript timers.

4. Security Review

This module performs automated testing for security vulnerabilities against traditional attackers. It does not actually make your site secure and locked down, but runs a series of security checks for arbitrary PHP execution, protection against XSS and a lot more, and provides solutions to fix issues.

5. Username Enumeration Prevention

Attackers can easily find usernames with loopholes in the system to access the Drupal site with username enumeration. Attackers can enter a username that does not exist or use the ‘forgot password form’ to get a confirmation message stating that the auth credentials are invalid. When the attacker persists by trying entering random usernames until the valid username has been found. This module will will make it impossible for the attacker to access the Drupal website. When this module is enabled, the error message will be replaced for the standard unknown username and the user will be redirected back to the login form. If the user does not exist, no password reset email will be sent. The attacker
Can no more exploit the username.

6. Security Kit

This module is reliable, user-friendly and provides Drupal with various security hardening options that can be used in your Drupal site to protect against different web application vulnerabilities. This module promises security for cross-site scripting, cross-site request forgery, clickjacking, and SSL/TLS.

Use these six Drupal modules to get maximum protection to your website from unwanted hackers and attackers. Keep your Drupal site safe and secure with all these modules, we would also recommend you to ensure the perfect dose of Drupal development needs with Anubavam.

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.

modules/custom
modules/contrib

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

Custom Module

 

Create a custom module

Module name: example

Info.yml

Drupal 7 - example.info (module_name.info) to store metadata about the module.
Drupal 8 - example.info.yml (module_name.info.yml) to store metadata about the module.

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

Example:

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

routing.yml

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

Example:

example.icecream_list_page:
  path: '/icecream/list'
  defaults:
    _controller: '\Drupal\example\Controller\IcecreamController::icecreamPage'
    _title: 'My Custom Icecream Page'
  requirements:
    _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

IcecreamController.php

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

<?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

<?php 
/** 
 * @file
 * File description
 */
?>

Twig

{# 
/** 
 * @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

Variables

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 }}
{{ user['name'] }}

Printing a variable

PHP Template

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

Twig

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

Printing a hash key item

PHP Template

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

Twig

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

Assigning a variable

PHP Template

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

Twig

{% set new_var = content.comments %}

Assigning an array

PHP Template

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

Twig

{% 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'} %}

Conditionals

PHPTemplate

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

Twig

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

PHPTemplate

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

Twig

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

PHPTemplate

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

Twig

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

PHPTemplate

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

Twig

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

Filters

Check_plain:


PHP Template

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

Twig

{{ name|striptags }}

Translate
 

PHP Template

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

Twig

{{ '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.

Parameters:

  twig.config:
    debug: true

Dump

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) }}

Empty

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 %}
    * {{ region.name }}
{% 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

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:

Example

<h1>List</h1>
<ul>
    {% for region in regions %}
        <li>{{ region.name|e }}</li>
    {% endfor %}
</ul>

Example

The if tag can be used to test an expression:

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

Comments

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 %}
#}

 

Drupal 7 users usually struggle to set up an effective system of moving to live sites. If you change any settings on a development  site, it is very difficult those settings to move live. Drupal 8 new configuration system is set to resolve all these issues Drupal developer is facing.

Drupal 8 provides new ways to tailor and deploy content that looks great on any mobile device. However when you work with Drupal, there is always something is there in Drupal 8 for you to love.

Code driven development in Drupal 8

Drupal 6: Features module is used export configuration to PHP code.
Drupal 7: Features modules brings more functionalities, but relying on third parties and it is incomplete.
Drupal 8: Content and configuration are being separated and configuration is text-based.

Drupal 8 Configuration Management System
In Drupal 8 new configuration system it is easy to get a copy of the development site with the changes and import those changes into the live sites.

There are two types of configuration in Drupal 8:

  1. Simple configuration
  2. Configuration entities

Simple Configuration

Simple configuration will store the basic configurations such as integers, boolean values or texts. Simple configuration has one version, and similar to using variable_set()  and variable_get() in Drupal 7.

Configuration Entities

Configuration entities including content types will enable the creation of zero or more complex. Examples of configuration entities contains content types, views and image styles.

Configuration can override in settings.php as in drupal 7. These overridden $config variables has high priority than values provided by modules. It is a good method for storing sensitive data.

The configuration system implements Drupal\Core\Config\ConfigFactory::get() to override $config variables.

How Configuration Management Works?

Configuration files are found inside the /config/install/ directory. These files will be created when a module is first installed and will not be used on module update.

After installing Drupal 8, two random named directories will be created in the public files folder. Generally that will mean the directory for sync files is in /sites/default/files/  and can change this location by an instruction.

 

An active directory is to keep currently active configuration. Active configuration will be stored in the database and done by the way for performance and some security reasons. Also it can push the configuration storage to use the file system using Configuration Tools module.

The staging directory is the place from where the configuration is synchronized/imported and it is empty until the configuration will be exported/imported.

Drupal 8 UI For Configuration management  
Configuration > Configuration synchronization.

Synchronize: Synchronize the changes from a file that you have imported.
Import: This allows you to import sync changes from the other sites.     

User interface settings for Configuration Management are very easy, but still have significant limitations such as:

  • Can't select multiple component at once and can't select a content type as well as multiple fields.  
  • Single features can't be exported into a file and can copy-and-paste the details.

Features module can be used for more advanced configuration management system. Import configuration settings can't be done until both the exporting and importing sites should have exactly the same UUID.

Drush Configuration Management
Drush is a wonderful shell interface to manage Drupal cloud server command line. It is a very useful tool to perform various tasks using a single or few commands, and to avoid many clicks and page refreshes in the UI.

Drush config commands used In Drush 8
drush config-export - exports the configuration to your sync directory.Current contents of your export directory (called "sync" by default) will be deleted.
Config-export - Export the configuration to a directory.

 

Do you want to provide better services to students and faculty and expand your institution globally? Bring your community closer with a right education solution that is designed to help institutions create pre-designed forms & letters, search for course catalog, provide mobile access and boost communication between faculty, students, management, and parents and more. Go through this blog and find major reasons for having a content management system for your college or university!
 
Drupal is one of the most popular content management system across the world and is currently being adopted by massive organizations like the Whitehouse, McDonald’s, The Economist and many others. The key pain points in higher education institutions is its inability to connect and collaborate with its stakeholders. Moreover, it is becoming increasingly difficult to customize website to reflect their brand. Colleges and Universities are moving to Drupal and focused on recruitment and retention of students.  With Drupal development, institutions can achieve huge cost savings and improve productivity. Here’s a list of ten instances why Drupal solution is appealing to higher education institutions:
 
Multi-user content management
 
Drupal has a user-friendly interface that allows students, faculty, management, staff and parents to upload data, share any media and spin up a new site in minutes. 
 
Profiling
 
Students and faculty can create and edit profiles with unlimited custom categories and fields including demographic data, enrollment, schedule and more, and share academic records with administrators.
 
Highly secure
 
Role-based security access to information enable college administrators to control data shared between students, teachers and parents. 
 
Reusable content
 
Providing your institute community with an online and mobile alternative allows students, staff and faculty to create and reuse content through faculty pages, photo gallery, streaming videos, directories, blogs, news, and events. 
 
Customizable
 
Drupal is highly customizable, scalable, flexible, feature-rich and high performance website with unmatched user experience to meet the needs of 21st century education institutions.
 
Automated workflow tools
 
Drupal allows individual users to automate repeat tasks through auto-assignment & approval processes, WYSIWYG form, role-based access control, KPI-based reports, automatic status tracking, notifications, and more.
 
Search engine friendy
 
Drupal allows you to optimize massive amount of content for major search engines such as Google, Bing, and Yahoo and help you to build your brand and improve online reputation.
 
Surveys & feedback forms
 
Create custom forms and fields using Drupal web forms to collect information for registration, faculty/course evaluation, surveys, polls, questionnaire, quizzes, feedback, and more.
 
Mobile accessibility
 
Using mobile-first and responsive design techniques, Drupal offers the best way to deliver website content on different mobile and tablet devices with the least learning curve. Drupal to mobile service provides an easy way to build a multi-platform mobile app for iOS and Android with user-friendly design and native-look alike.        
 
Social media 
 
Drupal makes it easy to integrate all of the social media platforms such as Facebook, Twitter, LinkedIn, Pinterest and more. Students, faculty, staff and alumni can share content and improve their interactions across social channels.  
 
Multilingual support
 
Drupal provides multilingual support and enable education institutions to make available website in multiple languages with good content translation and reach out to overseas students to drive website traffic, increase enrollment and gain competitive edge.  
 
If you need a College Management System designed for the unique complexities of higher education optimized for colleges & universities, then Anubavam offers the right Drupal solution for your institution.  Anubavam is an expert Drupal development company that has built a diverse range of websites and mobile apps for a wide range of global clients and enterprises, ranging from small and large corporations to Fortune 500 companies.
 
Subscribe to Drupal developer
 

start with anubavam today

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

Request Quote