Drupal Context Module: How to

Drupal context module
Drupal context module

Drupal is the magic CMS to build a website really fast. Using Drupal modules like views, panels, context, display suites, you can create a website almost without writing any code.

 

Today we will discuss the functionality of context module. Consider the following statements.

 

  • If your age is between 13 and 19, then you are a teenager.
  • If you are a pragmatic programmer, then you are a hard worker.
  • If the page URL starts with ‘en’, then set the language context to ‘English’.

 

We know these statements (if <condition>, then <action>) are very common in Drupal development. Using context module, you can implement this kind of conditional statements and their actions very easily without writing any code.

 

Lets see how.

 

Install the module and dependencies

 

drush dl context, ctools

drush en ctools, context, context_ui –y

 

Context module is dependent on ctools module, so install ctools as well. Enable Context UI for context administration purpose.

 

Create a context

 

  • Login to your site as an administrator.
  • Go to ‘Administration > Structure > Context’.
  • Click on ‘Add’.

Name your context

 

Name your context. It has to be unique.

 

We recommend follow the variable naming convention (no space, small letters, no special characters, underscores not dashes). That way you will be able to export, import your context using features.

 

Setup conditions.

 

Setup Context ConditionsSome example conditions that you can setup are:

 

  • If the path is …
  • If the language is …
  • If the taxonomy term is …
  • If the taxonomy vocabulary is …
  • If the value of a date field is …
  • If content type is …
  • If logged in user role is …
  • If the organic group of the content is …
  • Etc

 

Setup Reactions

 

Some example reactions:

 

  • Publish a block
  • Set breadcrumbs
  • Set OG group context
  • Set some meta data
  • Exclude the page from search engines etc
  • Disable some theme region for the page
  • Set a CSS body class for the theme etc

 

 

Well, these conditions and reactions are not all. You can implement your own custom context conditions and reactions using Drupal context API. We will discuss that one the other day.

 

Happy Drupaling 🙂

 

Leave a Reply

Your email address will not be published. Required fields are marked *