Website personalization takes into account that users have different motivations, devices, locations and time constraints. With current technology, marketers can now gather specific information about what a website visitor is searching for and translate their visit into a higher conversion.
Itai Sadan, co-founder and CEO of DudaMobile, a mobile website creation platform states: “Organizations spend tens or hundreds of thousands of dollars, and sometimes even millions of dollars, to create robust dynamic web experiences”
DudaMobile recently released inSite, a service that adds dynamic web content to pages based on the customer’s behaviour in a bid to create personalized viewing experiences.
Here is a list of five ways companies can start to increase their conversion rate through website personalization:
Visitor frequency can change your conversion rate
Visitor frequency often determines different user experiences. A first time visitor will most likely look for different information than someone who has visited the site repeatedly.
LegalAdvice’s marketing officer David Reischer suggests that tracking each user individually can offer visitors different user experiences: “We utilize a cookie to track a returning visitor so that we can direct them to the most appropriate and relevant page. This makes site navigation easier for repeat users.”
First time visitors should have access to a contact form to capture leads, a phone number or business address or a video tutorial that explains a service or product.
DudaMobile’s CEO explains the system for frequent visitors: “For frequent visitors, add a spot to sign up for a mailing list or add information about new products or services”
Geo-location is also important
Geo-location blends offline and online marketing. Knowing where your user is located when visiting your website is a game changer for marketers – “Online we can follow our customer’s individual buying journey, optimizing it every step of the way” explains Bart Heilbron from BlueConic. He continues: “However, we were never able to use these insights in our offline interaction. With geo-location, we are now able to.”
If a potential customer is visiting your website from a very close distance there’s a high chance they will become a customer if they see an address and a coupon that says “Come in today and get 20% off”. Restaurants can use an open table button to make reservations quickly or a Google Map that provides directions to the businesses location.
Always adjust your content
Adjusting your content to certain seasons, weeks or to your particular business hours can increase your conversion rate as well. You can replace your phone number with a contact form during the time your business is closed – this can help you avoid missing out on potential customers who want to reach you outside business hours.
“The ability to offer different products over the course of a day based on targeted trends, habits or culture will increase conversions,” said CEO WebiMax, Ken Wisnefski. “For example, a restaurant offers a different menu throughout the day as they switch from lunch to dinner.”
Recognize special events and holidays
Recognizing special events or holidays is a great way to connect with your customer and personalize your website. You can change your website’s theme during Valentine’s Day or during the 4th of July. “This could have a positive effect on customer engagement, and in turn conversion,” said Sadan from DudaMobile.
Adapt your content to your visitor source
Knowing your visitor source and adapting accordingly can have a great impact on your conversion rate simply because you can create dedicated landing pages for your potential customers. According to Sadan, “Visitors that come to your site from an email marketing campaign or as a referral from another site should receive dedicated messaging that is aligned with the messaging they saw in the email or the referring site. Offering a coupon at this point could also be a good idea.”
Adrian Ababei / Mar 07'2016
When it comes to mobile development, it’s much easier to create a brand new responsive website than to upgrade an existing website from unresponsive to responsive. That being said, the task is definitely doable if you follow these mobile development tips:
This is a list of different mobile development methods which you can use to roll out a responsive redesign.
Responsive retrofit
If retrofit works on your current project or website, it’s a great option for quick mobile development. It’s definitely not a magic wand but you can definitely retrofit an existing desktop website to a mobile one in a relatively short period of time – some projects can last under two months while some can last just a few weeks.
Parallel beta
You should definitely use a beta and have your users test it out in order to make sure you get the right results. Mobile development companies use this method to get a lot of user feedback and implement different solutions to fix potential problems.
Mobile-only responsive
Similar to the parallel beta method, using an existing m-dot site to experiment and gain user feedback is a great idea. The existing m-dot website can be used as a sandbox for rolling out responsive design in stages. This method was used by BBC and the Guardian to upgrade their websites, so you know you’re in good company.
Conclusions
With the number of mobile users surpassing desktop users, it’s essential for any organisation or company to have a fully functional responsive website to handle this new trend.
Adrian Ababei / Mar 05'2016
Web development experts tend to debate a lot when it comes to Javascript vs jQuery. There is really no correct answer in this situation simply because either of them can be used to create approximately the same effects or results - it’s contextual.
Generally speaking, jQuery should be enough for your average web development project but in certain cases JavaScript may be necessary to successfully complete it. As a rule of thumb, every web developer should learn both jQuery and JavaScript so let’s get down to the details:
Javascript
Javascript is a web programming language that’s oriented on objects. The programming language is usually used to introduce certain functionality into web pages. The Javascript code is automatically loaded by the browser. Javascript is very similar to C when it comes to syntax – it’s very popular among programmers because you can create scripts for multiple activities such as adding effects or creating menus on certain page elements.
Asynchronous Javascript and XML, also known as AJAX is becoming more and more popular in the programming world. With this technique, HTTP requests are made in the background, without needing to reload the page – changes to certain sections of the page are done in real time. When using AJAX, programmers can create interfaces with limited response time simply because the time for reloading a HTML page is removed.
jQuery
jQuery was released back in 2006 as a library build with Javascript – jQuery helps web developers load dynamic content onto pages, handle events, manipulate CSS and animate certain page elements. If you’re using jQuery you won’t have to worry about how browsers interpret the code. jQuery is a very useful Javascript library that reduces vague code and collects functions which in turn increases your programming workflow.
jQuery 1.x is supported by Internet Explorer 6 or higher and all browsers in general. With jQuery 2.x, the support for IE 6-8 was dropped but instead jQuery supports Internet Explorer 9 or higher.
The jQuery user interface is a collection of GUI Widgets, visual effects and themes created using jQuery, HTML and CSS.
jQuery UI effects include:
Add Class, Toggle Class, Remove Class, Switch Class
Color Animation
Effect
Hide, Show
Toggle
jQuery UI Widgets include:
Accordion
Autocomplete
Button
Datepicker
Dialog
Menu
Progressbar
Selectmenu
Slider
Spinner
Tabs
Tooltip
jQuery UI utilities include:
Position
Widget Factory
Javascript code:
function backgroundChange(color) {
document.body.style.background = color;
}
Onload=” backgroundChange(‘blue’);
Where as in jQuery the code is much simpler and clean:
$(‘body’).css(‘background’,’blue’);
Javascript vs jQuery – Which one to use?
For most web development projects jQuery will suit your needs just fine but as stated before, learning both Javascript and jQuery can be an asset. Keep in mind that one of the biggest differences between Javascript and jQuery is the fact that jQuery can work with many browsers automatically while JavaScript has cross browser compatibility issues due to poor implementation practices.
Adrian Ababei / Mar 03'2016
HTML 5 is currently the latest version of the Hypertext Markup Language. Unforunately, it’s not yet supported by all of the popular browsers, especially when we’re talking about older versions of popular browsers such as Firefox or Chrome. That being said, HTML4 is supported by every browser available, which gives it a bit of an edge.The doctype declaration is also much shorter in HTML5:< !DOCTYPE HTML >As compared to HTML4’s doctype declaration:< !DOCTYPE html PUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN""< html" >http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >< html lang="ar" dir="ltr" xmlns="" >http://www.w3.org/1999/xhtml" > HTML also boasts new tags such as:< audio >< video >< article >< nav >< header > What this means is that you won’t use the same tag for everything, as previously done in HTML4 – these tags offer a standardized structure and makes them easier to read.Footer and Header tags don’t only mark the end or the start of a page but can mark the end or start of a section as well. Basically, you can find multiple instances of these tags on the same page you’re working on.Some tags from HTML4 have been found redundant and thus have been removed from HTML5 – browsers don’t support these tags so it’s a good idea to have them removed:< acronym >< applet >< basefont >< big >< center >< dir >< font >< frame >< frameset >< noframes >< strike >< tt >HTML5 also offers error handling, a feature which was much desired by web developers for years – this basically means that each browser you test will give you the same error if something doesn’t work right. Meanwhile, HTML5 is constantly growing and developing, you won’t hear about the “finished” version of it anytime soon – it just gets better and better. With HTML5 you can use 3D or 2D effects and graphics, allowing you to create more interesting projects.HTML5 video is starting to replace Flash very quickly – YouTube started using it due to its better optimization and less resource use. Another advantage HTML5 has over Flash is that it doesn’t require any installation and devs don’t need certain tools to write code, as is the case with Flash. Some developers may prefer Adobe Dreamweaver but it’s not really needed. Edge is a HTML5 animation tool specifically designed to produce animations very similar to Flash.
Adrian Ababei / Feb 25'2016
The concept is simple: you can use more complex CSS files that could contain variables, functions, “mixins” and other things, too. These files would be compiled after development into normal CSS files supported by all the web browsers out there. First, you would ask yourself: “Why should I use a more complex CSS, if the old and simple CSS works just fine?”. The main answer for this question is quite simple: because it simplifies your work, you will write less. For a more detailed answer, I will write some reasons why a preprocessor is better: - regular CSS is a very simple language: you have selectors for targeting elements and you style these elements with different properties; yes, this would make the language more friendly for amateurs and designers (even if they don’t have experience with computer programming), but this forces you to do things the long way - with CSS preprocessing you can start using variables and functions, this will allow you to reuse parts of your code over and over again - you wouldn’t repeat yourself anymore CSS example: .simple { font-size: 20px; font-weight: 600; line-height: 1.3em; text-transform: capitalize; } .simple-red { font-size: 20px; font-weight: 600; line-height: 1.3em; text-transform: capitalize; color: red; } .simple-blue { font-size: 20px; font-weight: 600; line-height: 1.3em; text-transform: capitalize; color: blue; } The same code using Less: .simple { font-size: 20px; font-weight: 600; line-height: 1.3em; text-transform: capitalize; } .simple-red { .simple; color: red; } .simple-blue { .simple; color: blue; } - as you can see, nothing is repeated, that means you will save a lot of time and you can use this time for other things - you will update your code easier (besides the fact that you don’t need to remember some things) For example, you can define variables for colors like this: $red: #FF0000; $blue: #0000FF; After that, you can use them for different elements, for example: h1 { color: $red; } h2 { color: $blue; } If you decide that $blue is not ok and you want to change it, you only modify it once at the beginning and it will work for all your code. - your CSS code will be more organized, both LESS and SASS support nested definitions; for example: Normal CSS: p { color: red; font-size: 15px; font-weight: 600; } p span { color: blue; font-size: 16px; font-weight: 300; } p span:hover { color: #FFF; text-decoration: underline; } Using a preprocessor: p { color: red; font-size: 15px; font-weight: 600; span { color: blue; font-size: 16px; font-weight: 300; &:hover { color: #FFF; text-decoration: underline; } } } - it’s easy to use; for example, for SASS you would write a simple command line to watch for your SASS files and compile them automatically if you would modify anything - you will spend more time to make your website prettier (using the time you saved) - it’s easy to use, you will learn it faster than you think - you can use frameworks, the most popular one, Compass, automatically generates vendor-specific CSS properties and has lots of useful functions
Adrian Ababei / Feb 16'2016
Every web page on the internet can have proper HTML headings. These headings are identified by the following heading tags <h1> <h1> <h2> <h3> <h4> <h5> and <h6> where the „h” stands for heading.
HTML Headings – Why use them?
Heading tags are used for two important things:
Firstly, headings are a great way of making titles and subtitles visible for your visitors or users. It can also be used to summarize the next paragraphs and help your visitors understand what they will read under the heading.
Secondly, headings are used to indicate the most important pieces information on your page to search engines. Some SEO experts seem to think headings are not that important when it comes to optimization but every little bit helps.
Here are the rules
HTML headings on a page need to follow certain rules, as follows:
Each HTML page can contain one or more H1 to H6 tags
Each HTML tag needs an opening tag and a closing tag - <h>yourheading</h>
There are six possible levels of tags in total: h1, h2, h3, h4, h5 and of course h6, h1 being the first level heading and most important one and h2 being the second level heading, h3, the third level heading and so on.
HTML Headings – Best Practices
Here are two examples of properly used HTML headings for a test page:
<h1>Your-title<h1>
<h2>Your-subtitle<h2>
<h3>Your-sub-subtitle<h3>
<h4>Your-sub-sub-subtitle<h4>..etc.
This page example now has the main title in H1 and less important but still relevant titles or summaries in tags such as H2, H3, H4, etc. Keep in mind that this template can only be used on certain types of content. If your content doesn’t allow H1, H2, H3, H4 splitting, you can opt for a different approach and still use headings properly.
Another way you can properly use HTML headings is as follows:
<h1>Your-title<h1>
<h2>subtitle-1 <h2>
<h2>subtitle-2 <h2>
<h2>subtitle-3 <h2>
<h2>subtitle-4 <h2>
In the example above subtitle 4 is just as important as subtitle 2, but not as important as the title. With this template you are telling search engines that all sub titles on your page are equally important – this heading template maintains good readability and structure.
HTML Headings – The wrong way
Sometimes people make mistakes when it comes to their proper use of HTML headings. It can happen when you are trying to make a subtitle text bigger with a heading – don’t do it, just increase the font size. Here is an example of poorly used HTML headings:
<h1>Your-title<h1>
<h3>subtitle-1 <h3>
<h4>subtitle-2 <h4>
<h2>subtitle-3 <h2>
<h3>subtitle-4 <h3>
In this example, we start with H1 and then H3, H4, back to H2 and back to H3. Always keep in mind that HTML headings need to be logical – imagine it as a book where H1 is the title and H2 can either be a chapter or a sub-chapter.
Adrian Ababei / Feb 16'2016
Drupal development is becoming an increasingly popular choice for developers all around the world. This has sparked the interest for upgrades for this technology. Drupal used to work with the PHPTemplate engine which sought to separate the presentation layer from the logic layer. Recently Drupal development took one step further by replacing PHPTemplate with Twig, the latter being more secure and powerful.
Twig & Drupal Development
With Drupal 7, text previously submitted by the user needed the check_plain() function in order to prevent the ever-present vulnerability of cross site scripting or XSS.
If a theme’s output wasn’t sanitized, it was a huge security risk. Autoescaping was recently accepted into Drupal 8 as well, which made Drupal development much safer.
PHP functions are also removed from templates, in line with separation of concerns. Here is the new Drupal development mark-up:
Old: <?php print render($content); ?>
New: {{ content }}
The new syntax makes Drupal development faster and cleaner, a clear separation between presentation and logic with an added security boost. Twig offers many other benefits including that of inheritance – this has been called one of Twig’s biggest assets.
By integrating Drupal development with Twig, the need to copy and paste the parent theme template files into custom templates is eliminated. Twig limits the amount of template code and files you need to organize within your theme.
{% extends "themes/sub_bartik/templates/node.html.twig" %}
This is quite similar to PHP’s „include function” – it allows you to create hookable, dynamic templates. But there’s another feature which makes Twig great: Twig blocks
Parent file:
{# This empty block allows child templates to insert markup into this place in the header without re-writing the entire template. #} {% block header_fields %} {% endblock %}
New file:
{# Override the header_fields block to put field_image there because this site needs it there. #} {% block header_fields %} {{ content.field_image }} {% endblock %}
With the use of Twig and Twig blocks, Drupal development will become much easier – this also makes Drupal websites much safer and powerful.
Adrian Ababei / Oct 23'2015
Security is very hard to bolt on to any software or product after it has been built. Building it into the core of the code helps to avoid mistakes, and thus the upcoming release of Drupal 8 tries to build in more security by default, while still being usable for developers and site builders. This list of 10 security improvements is not exhaustive - some are just a line or two to handle an edge case, and there are others I may have overlooked. I've contributed to a number of these improvements, but they reflect overall the community consensus as well as reactions to problems that required security releases for Drupal core or contributed modules in the past. For each point I've tried to include a link or two, such as the Drupal core change record, a documentation page, or a presentation that provides more information. Some of these may also be possible to back-port to Drupal 7, to benefit you even sooner. A "7.x back-port" link indicates that. For context on why these 10 improvements are important, I looked at past security advisories (SAs) as well as considering the kind of questions we get here at Acquia from companies considering adopting Drupal. In terms of past SAs, cross-site scripting (XSS) is the most commonly found vulnerability in Drupal core and contributed modules and themes.
1. Twig templates used for html generation
This is probably first on the list of anyone you ask about Drupal 8 security. This is also one of the most popular features with themers.
One security gain from this is that it enforces much stricter separation of business logic and presentation – this makes it easier to validate 3rd party themes or delegate pure presentation work. You can't run SQL queries or access the Drupal API from Twig.
In addition, Drupal 8 enables Twig auto-escaping, which means that any string that has not specifically flagged as safe will be escaped using the PHP function htmlspecialchars() (e.g. the same as Drupal 7 check_plain()). Auto-escaping of variables will prevent many XSS vulnerabilities that are accidentally introduced in custom site themes and custom and contributed modules. That fact is why I ranked this as number one. XSS is the most frequent security vulnerability found in Drupal code. We don't have a lot of hard data, but based on past site audits we generally assume that 90% of site-specific vulnerabilities are in the custom theme.
2. Removed PHP input filter and the use of PHP as a configuration import format
OK, maybe this should have been number one. Drupal 8 does not include the PHP input format in core. In addition to encouraging best practices (managing code in a revision control system like git), this means that Drupal no longer makes it trivial to escalate an administrator login to being able to execute arbitrary PHP code or shell commands on the server.
For Drupal 7, importing something like a View required importing executable PHP code, and for certain custom block visibility settings, etc. you would need to enter a PHP snippet. These uses of evaluated PHP (exposing possible code execution vulnerabilities) are all gone – see the next point about configuration management.
Now that we have covered the top two, the rest of the 10 are in rather arbitrary order.
3. Site configuration exportable, manageable as code, and versionable
The Configuration Management Initiative (CMI) transformed how Drupal 8 manages things that would have been represented in Drupal 7 as PHP code. Things like Drupal variables or ctools exportables (e.g. exported Views).
CMI uses YAML as the export and import format and the YAML files can be managed together with your code and checked into a revision control system (like git).
Why is this a security enhancement? Well, in addition to removing the use of PHP code as an import format (and hence possible code execution vulnerability), tracking configuration in code makes it much easier to have an auditable history of configuration changes. This will make Drupal more appealing and suitable for enterprises that need strict controls on configuration changes in place. In addition, configuration can be fully tested in development and then exactly replicated to production at the same time as any corresponding code changes (avoiding mistakes during manual configuration).
Finally, it is possible to completely block configuration changes in production to force deployment of changes as code.
4. User content entry and filtering improved
While the integration of a WYSIWYG editor with Drupal core is a big usability improvement, extra care was taken that to mitigate poor practices that adding a WYSIWYG editor encouraged in past Drupal versions. In particular, users with access to the editor were often granted access to the full html text format, which effectively allowed them to execute XSS attacks on any other site user.
To encourage the best practice of only allowing the use of the filtered HTML format, the Drupal 8 WYSIWYG editor configuration is integrated with the corresponding text filter. When a button is added to the active configuration, the corresponding HTML tag is added to the allowed list for the text filter.
Drag a new button from the available to enabled section in the editor configuration: WYSIWYG editor configuration adding underline button The corresponding HTML tag (the U tag) is added to the allowed list: U tag is allowed in the filter An additional security improvement is that the core text filtering supports limiting users to using only images local to the site which helps prevent cross-site request forgery (CSRF) and other attacks or abuses using images.
5. Hardened user session and session ID handling
There are three distinct improvements to session and session cookie handling. First, the security of session IDs has been greatly improved against exposure via database backups or SQL injection (7.x back-port ). Previously in Drupal, the session ID is stored and checked directly against the incoming session cookie from the browser. The risk from this is that the value from the database can be used to populate the cookie in the browser and thus assume the session and identity of any user who has a valid session in the database. In Drupal 8, the ID is hashed before storage, which prevents the database value from being used to assume a user's session, but the incoming value from the value is simply hashed in order to verify the value.
Next, mixed-mode SSL session support was added to core to support sites that, for example, used contributed modules to serve the login page over SSL while other pages unencrypted. You will have to replace the session handling service if you really need this. This encourages serving your entire site over SSL (which is also a search engine ranking boost).
The final change is that the leading “www.” is no longer stripped from the session cookie domain since that causes the session cookie to be sent to all subdomains (7.x back-port).
6. Automated CSRF token protection in route definitions
Links (GET requests) that cause some destructive action or configuration change need to be protected from CSRF, usually with a user-specific token in the query string that is checked before carrying out the action.
This change improves the developer experience and security by automating a process frequently forgotten or done incorrectly in contributed modules. In addition, centralizing the code makes it easier to audit and provide test coverage. Drupal 8 makes it easy. A developer merely needs to specify that a route (a system path in Drupal 7 terms) require a CSRF token. Here is an example of the YAML route definition for a protected link in Drupal 8 entity. entity.shortcut.link_delete_inline: path: '/admin/config/user-interface/shortcut/link/{shortcut}/delete-inline' defaults: _controller: 'Drupal\shortcut\Controller\ShortcutController::deleteShortcutLinkInline' requirements: _entity_access: 'shortcut.delete' _csrf_token: 'TRUE' Only the one line in the requirements: section needs to be added to protect shortcut deletion from CSRF.
7. Trusted host patterns enforced for requests
Many Drupal sites will respond to a page request using an arbitrary host header sent to the correct IP address. This can lead to cache poisoning, bogus site emails, bogus password recovery links, and other problems with security implications. For earlier versions of Drupal, it can be a challenge to correctly configure the webserver for a single site that uses sites/default as its site directory to prevent these host header spoofing attacks. Drupal 8 ships with a simple facility to configure expected host patterns in settings.php and warns you in the site status report if it's not configured.
8. PDO MySQL limited to executing single statements
If available, Drupal 8 will set a flag that limits PHP to sending only a single SQL statement at a time when using MySQL. This change would have reduced the severity of SA-CORE-2014-005 (a SQL injection vulnerability that was easily exploited by anonymous users) (7.x back-port)
. Getting this change into Drupal 8 meant I first had to contribute a small upstream change to the PHP language itself, and to the PDO MySQL library that is available in PHP versions 5.5.21 or 5.6.5 and greater. There is also a patch in progress to try to enforce this protection regardless of which specific database driver is being used.
9. Clickjacking protection enabled by default
A small change, but Drupal 8 sends the X-Frame-Options: SAMEORIGIN header in all responses by default. This header is respected by most browsers and prevents the site from being served inside an iframe on another domain. This blocks so-called click-jacking attacks (e.g. forms or links on the site being presented in a disguised fashion on an attacker's site inside an iframe), as well as blocking the unauthorized re-use of site content via iframes. (7.x back-port).
10. Core JavaScript API Compatible with CSP
Support for inline JavaScript was removed from the #attached property in the Drupal render API. In addition, the Drupal javascript settings variables are now added to the page as JSON data and loaded into a variable instead of being rendered as inline JavaScript. This was the last use of inline JavaScript by Drupal 8 core, and means that site builders can much more easily enable a strict content security policy (CSP) – a new web standard for communicating per-site restrictions to browsers and mitigating XSS and other vulnerabilities. A final note of caution: The substantial code reorganization and refactoring in Drupal 8 as well as the dependence on third party PHP components does present a certain added risk. The code reorganization may have introduced bugs that were missed by the existing core tests. The third party components themselves may have security vulnerabilities that affect Drupal, and at the very least, we need to track and stay up to date with them and fix our integration for any corresponding API changes. In order to try to mitigate the risk, the Drupal Association has been conducting the first Drupal security bug bounty that has been run for any version of Drupal core. This has uncovered several security bugs and means they will be fixed before Drupal 8 is released.
- Source: https://goo.gl/i2CCxj
Adrian Ababei / Oct 23'2015
The concept of Modular CSS has been around for years. The basic idea is tackling your CSS code in a systematic way through class and file naming conventions. The main goal being improved workflow through organization, readability and reusability. Some of the more recent modular CSS architectures are Object Oriented CSS (OOCSS) and Scalable and Modular Architecture for CSS (SMACSS). I tend to prefer SMACCS as Jonathan Snook has presented it as a set of guidelines rather than rules. He leaves it open for individual style and interpretation as every developer and every project is different. If you want to see a great example of Modular CSS in action, go blow your mind looking at the Twitter Bootstrap Components Library. The creators have done an excellent job abstracting the components in a way that makes them easy to understand and flexible via classes and subclasses. The idea of Modular CSS really appeals to me, especially having worked on large complex sites with multiple front-end developers collaborating together. While Drupal is perfect for these large scale projects, adding your own CSS classes to a Drupal theme ( essential when working with modular CSS ) is often unintuitive, inconsistent and tiresome at best. To remedy this, I've been working on a systematic approach to adding classes to themes that has so far proved extremely useful. In this post we're going to see how we can easily manage classes on one of Drupal's most used components, Blocks, using a preprocess function. Preprocess Functions Preprocess ( and Process ) Functions are the key to taking control of your classes in Drupal. Preprocess functions are called before every theme hook is sent to a theme function and template file (.tpl). In my mind preprocess functions have 2 uses: Altering and adding variables that are available to theme functions and .tpl's. This is how we'll be adding our classes. Sending these variables to an alternate theme function or .tpl via theme hook suggestions. I prefer managing my classes via preprocess functions over template files because I find it way more flexible and concise. I no longer need duplicate template files just to add or remove a single class. Adding Classes to Blocks As is often the case with Drupal, there are a few options out there for adding classes to blocks, including Skinr, Fusion Accelerator and Block Class. All of these offer the power of adding classes through the admin UI which may be right for you and your site administrators. This hasn't been a requirement for most sites I've worked on. Your mileage may vary. I prefer to define my classes directly in the theme where I'm already writing my CSS, everything is already in code and there is no need to export settings from the database. So let's see how we can do this using default core functionality. Looking at the core block.tpl.php file, by default there are 3 elements to which we can add classes during preprocess: the block container itself ($classes), the block title ($title_attributes) and block content ($content_attributes). As of this writing, in order to preprocess the block content classes, you must remove the hard coded class attribute from the template yourself or apply a core patch.
Now let's create our preprocess function and start adding some classes.
This may look like a lot but it's actually pretty simple. Let's break it down. First off, we create some shortcut variables to save us some typing down the road and make our code more legible. The first variable we create is $block_id which is just a string combining the name of the module creating the block and the block's delta— separated by a dash. This gives us an easy way to target individual blocks when we start adding classes. One thing to note, some blocks, including core custom blocks, use an auto-incremented integer for their delta value. This can present issues if you are moving blocks from dev to staging to production and you're not careful. I recommend using the boxes module to help mitigate this. The next three variables, $classes, $title_classes and $content_classes are references to the arrays that will eventually be rendered into class attributes. To add classes to an element, we just need to add them to its corresponding array. After we have our shortcuts set, we can started adding classes to our blocks. We first start by adding some global classes, .block-title and .block-content, to all block titles and block content containers respectively. You may or may not find this helpful. If you're interested in stripping out all the classes that core and other modules have added to your blocks up to this point, this would be the place to do it. To remove those classes, just reset your variable to an empty array like so $classes = array(); Next, we can start adding our classes on a per block basis. I like to keep a simple print statement handy that prints out the $block_id for all blocks on the page. When styling a new block, I just uncomment this line and copy the id from the browser into my code editor. To target individual blocks, we create a simple switch statement based on the $block_id. For each block we need to style, we write a case and add the corresponding classes there. In the first case we are adding three classes to the System Navigation block, one to the block itself, one to its title element and one to its content wrapper. In the second instance we are actually grouping two cases together so we can add the same classes to multiple blocks. Here we are adding .element-invisible, Drupal's built in class for hiding content in an accessible manner, to the titles of the Main Menu and User Login Blocks. As we add blocks, we add more switch statements. That's all we really need to do to take over our block classes. I've found this alone can be a tremendous boost to productivity while styling a Drupal site. You can get pretty far with blocks alone. However, with modifications to core theme functions and templates, similar to what we did with block.tpl.php above, this technique can be adapted to manage classes on nodes, fields, menus and most other themeable output. I've submitted a session proposal to DrupalCon Munich on this topic called Stay Classy Drupal - Theming with Modular CSS. If you're interested in learning more about taking control of your classes or have run into trouble trying to do so, leave a comment to let the organizers know you're interested in the session.
Adrian Ababei / May 06'2015