The Pros And Cons of Headless Drupal

Drupal is an excellent content management system. Nodes and fields allow site administrators the ability to create complex datasets and models without having to write a singe mysql query. Unfortunately Drupal’s theming system isn’t as flexible. Complete control over the dom is nearly impossible without a lot of work. Headless Drupal bridges the gap and gives us the best of both worlds.

What is headless Drupal?

Headless Drupal is an approach that decouples Drupal’s backend from the frontend theme. Drupal is used as a content store and admin interface. Using the services module in Drupal 7 or Core in Drupal 8, a rest web service can be created. Visitors to the site don’t view a traditional Drupal theme instead they are presented with pages created with Ember.js, Angular.js, or even a custom framework. Using the web service the chosen framework can be used to transfer data from Drupal to the front end and vice versa.

Pros

So what makes Headless Drupal so great? For one thing it allows frontend developers full control over the page markup. Page speed also increases since display logic is on the client side instead of the server. Sites can also become much more interactive with page transitions and animations. But most importantly the Drupal admin can also be used to power not only web apps but also mobile applications including Android and iOS.

Cons

Unfortunately Headless Drupal is not without its drawbacks. For one layout control for editors becomes much more difficult. Something that could be done easily via context or panels now requires a lot of custom fronted logic. Also if proper caching isn’t utilized and the requests aren’t batched properly lots of roundtrips can occur, causing things to slow down drastically.

Want to learn more about Headless Drupal?  Check out the Headless Drupal Initiative on Drupal.org.  And on a related topic, check out “Drupal 8 And The Changing CMS Landscape.

Ultimate Flexibility: Open Atrium’s New Related Content Feature

atrium-logo (1)The constant struggle between content editors and web developers:

  • Content editors want to embed rich media, callouts, and references to related content anywhere within their WYSIWYG.  They love the Body field and want more buttons added to the WYSIWYG.
  • Web developers want to add additional fields for media, attachments, related content to support rich content relationships and access control.  Web developers hate the Body field and wish they didn’t need a WYSIWYG.

In the latest 2.30 version of Open Atrium, we attempt to help both content editors and web developers with a new approach to building rich story content using the Paragraphs module.  Rather than having a single WYSIWYG body, content editors can build their story using multiple paragraphs of different types and layouts. The order of these paragraphs can be rearranged via drag and drop to create long-form content.

Site builders can add their own custom paragraph types to their sites, but Open Atrium comes with four powerful paragraph types “out of the box”:

(1) Text Paragraphs

OA2_Test_Paragraph

The simplest paragraph type is the “Text” paragraph.  It works just like the normal Body field with it’s own WYSIWYG editor.  But an additional Layout field is added to control how the text is rendered.  There are options for multiple columns of wrapping text within the paragraph (something nearly impossible to do with the normal Body field), as well as options for left or right floating “callouts” of text.

(2) Media Gallery

OA_Media_Paragraph

The “Media Gallery” paragraph handles all of the images and videos you want to add to your story.  It can replace the normal Attachments field previously used to add media to a document.  Each Media paragraph can contain one or more images, videos, or files.  The Layout field controls how that media is displayed, providing options for left or right floating regions, or a grid-like gallery of media.  Videos can be embedded as preview images or full video players.

When floating media to the left or right, the text from other paragraphs will flow around it, just as if the media had been embedded into the WYSIWYG.  To move the images to a different part of the story, just drag the media paragraph to a new position in the story.

In Open Atrium, images directly embedded into the Body WYSIWYG field becomes Public, bypassing the normal OA access control rules.  However, anything added to a Media paragraph works more like the Attachment field and properly inherits the access permission of the story document being created.  Thus, the Media paragraph provides a way to embed Media within your story while retraining proper privacy permissions.

(3) Snippets

OA_Snippet_Demo

The “Snippet” paragraph type allows you to embed text from any other content on your site.  You can specify whether the Summary, Body, or full Node is embedded and also control the Layout the same as with Text paragraphs.  You can also either display the Title of the referenced content or hide the title, or override the title with your own text.

One of the best features of Snippets is the ability to lock which revision you want to display.  For example, imagine you want to embed a standard operating procedure (SOP) within your story document.  You create a Snippet paragraph that points to the SOP.  However, if the related SOP node is updated in the future, you don’t want your old document to change.  For compliance purposes it still needs to contain the original SOP text.  By “locking” the snippet to the old revision, the old document will continue to display the original SOP even if the SOP is updated later.  If you “unlock” the snippet, then it will display the latest version of the related SOP.

Open Atrium access controls are also respected when displaying snippets.  If you reference content that the user doesn’t have permission to view, that snippet will be removed from the displayed text.  Users still only see the content they are allowed.  This provides a very powerful way to create rich documents that contain different snippets of reusable content for different user roles and permissions.  Similar to adding additional fields with Field Permissions, but much more flexible and easy to use.

(4) Related Content

OA_Related_Demo

The “Related Content” paragraph type is similar to Snippets, but displays the Summary or Full rendered node of the related content.  Like the Media paragraph, the Related Content can contain one or more references to other content on the site.  The Layout provides options for displaying the content as a table of files, or a list of node summaries (teasers), or as full node content.  When full node content is used, any paragraphs used in the related content will also being displayed (paragraph “inception”!).  In addition, any special fields from the full related node can be shown.  For example, a Related Event will show the map of the event location.  A Related Discussion will show all of the discussion replies and even provide the Reply Form, allowing you to reply to a related discussion directly from the story document itself!

Related Content is also a bi-directional link.  When you view the related content node, a sidebar widget called “Referenced From” will show all of the stories that reference the node being viewed.

A Real World Example

To pull all of this together with a real-world example, imagine that you are scheduling a Meeting.  You want to create an Agenda for that meeting and allow your team to discuss and edit the agenda before the meeting.  In Open Atrium you can now do this all from a single document:

  1. Create the Event for the Meeting, adding your team to the Notifications
  2. Add a Related Content paragraph for the meeting Agenda document
  3. Add a Related Content paragraph for the agenda Discussion

Open Atrium is smart about where this related content is created.  If you already have a section for documents, the Agenda will be created within that section.  If you already have a section for discussions, the related discussion will be placed there.  You can change these locations if you wish, but the default behavior reflects the most common information architecture.

When your team members receive the email notification about the meeting and click the link, they will be taken to your Event and will see the agenda document and discussion as if they were a normal part of the event body.  They can view the agenda content directly and can post replies directly into the discussion reply field.  They don’t need to go to separate places on the site to see the document or discussion.  If you *do* view the document or discussion nodes directly, such as from a search results page, you’ll see a link back to the meeting event in the References From list in the sidebar.

Conclusion

Not only do the Paragraph features help content editors build rich stories quickly and easily, they allow web developers to create related documents, linked content, better search results, better data structures.  It’s still not a magical unicorn wysiwig of content editor’s dreams, but it’s a significant step for Open Atrium and Drupal. It opens a whole new world of collaboration where all related content can be viewed together.

Looking for more information about Open Atrium? Sign up to receive Open Atrium newsletters and updates! Plus, get an in-depth look at Open Atrium’s new features in our winter release webinar – the recording is now available!

Join Phase2 for Drupal Global Sprint Weekend in NYC & PDX

This upcoming weekend, the global Drupal community is kicking off the New Year with sets of local sprints on January 17 and 18. The event is called Drupal Global Sprint Weekend, and as of this blog post there are almost 50 sprints scheduled all around the world. Phase2 is excited to be a part of this international event, hosting sprints at both our New York City and Portland offices and sponsoring a sprint at AnexusIT in Costa Rica.

Screen Shot 2015-01-12 at 10.07.09 AM

For the past 2.5 years, we’ve worked with Robbie Holmes to host Drupal community events, called Drupal Play Days, at the Phase2 office in New York City. Over time, the agenda has grown more diverse to include topics like SASS and Compass, Vagrant and Puppet, and of course Drupal 8. Our own Mai Irie has also used a lot of recent Play Days to hold planning meetings for NYCCamp events held at the United Nations.

This month, we are excited to combine our Drupal Play Day with the Drupal Global Sprint Weekend at the Phase2 offices. This means that you’re welcome to drop in, no matter your level in Drupal, from 9 AM to 5 PM. I repeat, you don’t have to be a Drupal developer to come out – all skill sets and skill levels are encouraged to participate. The plan is to split into pairs to work on Drupal core issues tagged with #SprintWeekend. Phase2 will provide Wi-Fi, heat, and food.

Please remember to sign up on the Drupal Groups event page, indicating if you will be sprinting in New York CityPortland, or Costa Rica, so that we can plan appropriately for food and seating needs. In the meantime, be sure to spread the word using #SprintWeekend on Twitter.

We can’t wait to see you this weekend! Don’t forget to bring your laptop ;)

Play with Display: Altering Drupal Field Collections

How do you insert a text field into a rendered entity, all within a field collection? This question came to mind on a recent Drupal 7 build. What at first sounded complicated turned into a concise and elegant solution.

The basis of the requirement broke down into the need for events to list those participating in the event. The build already had existing Event and Profile content types, so the new functionality would only require implementing the list of Profiles participating in an event. Each participant would include their role at the event, along with links to contact them.

blog

To implement this, an Event Participant field collection was added as a field to the Event content type. Each instance of the field collection included a single Profile content type and a single text field for their role at the Event. The Profile would then be displayed as a rendered entity within the field collection so that the Profile’s image and contact links could be displayed. The point at issue then arose. How would the Participant’s role at the event be placed within the rendered Profile teaser, along with the other Profile fields? To the user it needed to look like a single unified entity, with the Profile’s image, role at the Event, Profile name, and contact links all included.

Screen Shot 2014-12-11 at 4.27.43 PM.png

After some initial brainstorming a handful of different approaches came to mind. The initial impression was to use template_preprocess_field() since it allows the alteration of values in the theme layer. The participant role field would be removed from it’s initial location and inserted into the participant profile object. This did not work though. Despite the repositioning of elements within the render array, the changes occur too late in the rendering execution. The render array had already been rendered and thus the display remained the same.

After quickly realizing a theme function wasn’t the answer, hook_node_view() came to mind. The hook allows for the alteration of a node before it is rendered and so all that would be needed would be to shift the location of the Participant Role field within the $node array. The issue with this implementation and the reason it wasn’t chosen, is that it would require reaching out to the global state to determine what changes are needed. In other words hook_node_view() doesn’t realize what context it is called under and would thus require a hack of sorts to determine when it was being called under an Event node. This could be worked around by checking the URL path, but this is not best practice as it is brittle and prone to breaking with future site updates.

As they say the third time’s the charm. The final solution was to use hook_field_collection_item_view(). This hook allows for the alteration of a field collection item before rendering. Unlike many of the other options, this hook is called for each field collection item, allowing one to both check the field collection name and adjust it’s internal field ordering, before any rendering occurs. Using this hook, each Event Participant field collection item is altered, removing the Role field and inserting it into the Profile rendered entity. Simple as that. Now each Event Participant is correctly displayed as a single unified entity, with an image, name, and a set of contact links.

Through several quick, small, iterations an elegant, straight-forward solution was found to what at first sounded like a complicated feature request. Now users viewing an Event can see a list of Participants, with each Participant displayed as a single item. Check out more on field collections on the Phase2 blog!

Drupal 8 in a Changing CMS Landscape

Recently, I’ve noticed certain trends in our industry which I believe will greatly impact the evolution of Drupal. It’s undeniable: the CMS landscape is changing as the future of the web gears toward content APIs and other ways of interacting with a content storage system. As this shift deepens, all-in-one, full-stack Drupal packages will become less important than Drupal’s ability to integrate and operate with other content stores and applications that aggregate that content for display.

There are already numerous examples of this. Social integrations (with Disqus, for instance) allow social media conversation to happen directly on the page, but not in the CMS. Other integrations, like advertisements or the injection of third-party content, demonstrate how necessary it has become for a CMS to manage external content from multiple sources. Stock tickers and quotes are a perfect example, as they inject stock quotes from external sources into their CMS instead of aggregating that content internally. Those quotes are not generated or stored within Drupal – but Drupal allows site maintainers to easily manage the location and format of that data.

imagesDrupal has proven itself to serve as an excellent structured content store, and Drupal 8 will take that a step further by enabling better access and integration into the content store. As Drupal evolves to becomes more of a robust content repository, its ability to seamlessly integrate disparate content and data will likely out-weigh its prominence as a front-end rendering engine for HTML. The front-end itself is likely to move toward being a separate application altogether, likely based in a JS framework (e.g. Angular or React) or serving the ever-growing mobile landscape. Drupal is also moving in this direction by building front-end abstractions (like Twig) that are lighter, faster, and more suitable than developing a traditional Drupal theme. This provides an opportunity to create more efficient and speedy development cycles by integrating new tools for design in Drupal that reach the web more broadly. New tools like Pattern Lab and Mustache Templates can begin to extend Drupal’s front-end capabilities in new ways, further pushing Drupal’s value as a content store rather than an engine for creating websites.

Reuters Olympic Site Content EngineEnterprise media sites have taken the lead on embracing Drupal as a unified content repository. Thomson Reuters’ 2012 Olympic site, for example, expertly utilized Drupal as a content ingestion engine. By integrating with the company’s extensive content feed service, Media Connect, Reuters accumulated photos, videos, and text articles to populate and publish through a Drupal platform. In the coming years we will become the standard approach for more media and publishing properties, and I suspect that the “enterprise” will follow suit.

These developments have an inevitable outcome which is captured by the idea of COPE (“Create Once, Publish Everywhere”), a concept illustrated beautifully by NPR’s API. COPE isn’t a new concept, but the Drupal community has only recently begun to fully utilize it in terms of ingesting content from multiple sources, as well as publishing and distributing content through multiple channels. In the coming years, COPE will manifest in a number of ways, but for the purposes of this blog post I am focusing on content APIs as the most relevant implementation of COPE for the Drupal community (for now).

Content APIs in Drupal will bring about the clean separation between content creation, storage, and management, as distinct from the display of content. This separation allows managing content with a common mechanism, yet rendering it in through a variety of experiences. It will become commonplace to build user experiences using the myriad of flexible and dynamic front-end frameworks on top of a Drupal API, capturing the potent capabilities of Drupal as a content aggregation system. Not only will building multi-channel responsive applications with amazing design be much easier, but content creators will gain greater control over access to their content. Private companies, for instance, can sell access to valuable content, while government agencies can provide public access.

Drupal 8 is an important turning point, bringing Drupal closer to the decoupled, API-favorable content engine it will evolve into – a positive development. What changes do you see in the CMS landscape, and how will Drupal play a role? Comment below!

Drushful Thinking

What is Drush?

If you’re asking that question right now then congratulations! You are one of the lucky people who will have your life changed today! Cancel everything and read up on Drush, the command line bridge to Drupal.

Everybody knows about Drush, ya Dingus!

That’s more like it. Who doesn’t love Drush, right? Right!

But more and more, I find myself seeing people reinventing things that Drush already handles because they just don’t know all that Drush can do. It’s getting frustrating, and I want to fix that.

First, The Basics

Stuff everybody knows

Here are a few Drush commands that most people know and love, just to get them out of the way:

  • drush updb: run pending database updates
  • drush cc all: clear all caches
  • drush dl <something>: download the <something> module
  • drush en <something>: enable the <something> module

Stuff everybody knows (Features Edition)

And if you’re using Features, you’re probably familiar with:

  • drush fra: revert all Features
  • drush fe: export a new or updated Feature with a new component
  • drush fu <featurename>: update the <featurename> Feature with updated site config
  • drush fr <featurename>: revert the site’s config to the current state of the <featurename> Feature

Aliases

For a lot of the fun stuff, you’ll have to understand Drush aliases. If you don’t, here’s the gist: Drush aliases give you an easy way to run Drush commands on remote Drupal sites, as opposed to only being able to use it on your local sites. If you’re constantly SSH’ing into different environments just to run a couple quick commands, you need to stop doing that.

There’s lots of documentation about Drush aliases and how to create your own, but most of the docs lack notes on some of the lesser known awesome things you can do with aliases. Keep reading, sailor.

Well, one more thing. This is probably a good time to mention a couple quick commands.

Firstly, let’s run an arbitrary shell command on our dev environment.

Or maybe we should just go ahead and SSH in to do something a little more complex.

Or maybe we need to do a bunch of aliased commands, but we want to do it without SSH’ing in (because the commands require local files or something). We can make a Drush alias persist until we tell it to stop using:

And then when we’re done doing what we do, we can just run it again without the “@foo-dev” argument to unset it.

Now, keep reading, sailor.

Syncing Ship

(Warning: these headlines are going to get worse and worse)

One of the most common things to do with Drush aliases is to sync stuff from one alias to another.

For example, want to sync the dev site database down into your local?

How about files? Sync ‘em!

Or maybe some unwashed sent you a DB dump and you have to import it the old fashioned way?

Sometimes you want to drop your entire database before importing, to make sure you don’t get any tables left behind from your old install that aren’t supposed to be there. That’s as easy as:

Sometimes, it’s useful to be able to automate running arbitrary SQL commands on multiple environments, and that’s pretty easy too. Say for example that you quickly want to get the username for uid 1 on the prod environment (the “drush user-information” command would be much better for this, but shut up).

That one is also good for automation, like if you want to write a quick script that changes the username for uid 1 on all environments.

Drupal Without Drupal

It’s often useful to run one-off arbitrary code within the context of Drupal, without having to actually put it in the codebase somewhere. This is typically done one of two ways:

If it’s just a short one-liner, then there’s the ever-useful “php-eval” (aka “ev”) command. For example, let’s inspect a node object.

Or if it’s a longer one, then we can just throw our code into a PHP file, and run it using:

Reports Cohorts

Drush is really good at getting us information from Drupal without waiting for a full page load.

How many times have you navigated to the Watchdog page and sat through page load after page load while you went through the pagination and added filtering and blah blah blah to find an error message? Stop doing that! Do this instead:

There are a lot of useful options for watchdog-show, such as:

  • –tail (continuously show new messages)
  • –full (show the full output, with all of the fields, instead of the summarized version)
  • –severity (such as “–severity=error”)
  • –count (show more than the default 10, such as “–count=100″)

And I’d bet you’re familiar with “drush vget” to get variables, but did you know you can pass “–format=whatever” to get the results formatted as JSON or CSV or YAML or a bunch of other things, for easy scripting?

Another one of my favorites is this charm, which basically prints out the stuff you see on the Status Report page in Drupal. It’s nice for sanity checking before pushing releases live.

And then there’s this guy, which prints out a bunch of useful info about the current installation, such as DB info, path to PHP executable and .ini file, Drupal version, Drupal root, etc. It’s a nice first step when debugging a broken install.

And for those times when you need to edit a config file (php.ini, or settings.php, or an alias file, or .htaccess, etc.), you can run this to let you choose which of those files to edit and it’ll open it up in an editor for you:

Using Users

Drush is nothing short of a miracle when it comes to user management.

First of all, there’s the ever-annoying task of logging in as this user or that user. You usually don’t know the password, or maybe you’re just too lazy to type it. Run this to open up your browser with a one-time login link so you can skip all of that malarky:

Or, if you’re slightly less lazy, and just want to change the password to something so that you can log in the old fashioned way:

Then there’s the “fun” process of adding a user and filling out the form. Skip that:

Once that’s done, you probably want to give that new user some roles. For role stuff, you have this:

But watch out! The role you need to add doesn’t exist yet! Let’s add it, and give it some permissions.

If you just need to show information about a user, such as email address, roles, UID, etc., try this. I’m embarrassed to say that I’ve been using raw SQL for this for years.

Fields of Dreams

One of the most under-used things that Drush gives you is field management tools. I’m going to be lame here and just copy and paste the docs, since they’re pretty self explanatory.

Other Schtuff

Here are some great commands that don’t really fit into any clear-cut categories.

It has some neat archiving tools:

Somewhat similar to those is this one, which will download and install Drupal, serve it using a little built-in server, and log you in, all in one command. Note that this one includes about a bazillion options and is super duper powerful.

Drush also lets you play with the cache, which can save a lot of time when debugging a caching issue:

There are a couple unknown commands for working with contrib:

Run cron! Not exciting, but super useful.

Have you ever been in the middle of debugging and you know that something is happening in a form_alter (or some other hook) but you’re not sure in which module? Try this command, which will tell you all of the implementations of a given hook, and let you choose one to view the source code of it.

And finally, this bad boy is basically “Drush docs in a box” and has a TON of useful info. Seriously, try it now.

Drushful Thinking

There’s a giant heap of useful Drush commands, some of which you hopefully hadn’t seen before. So what, right?

The “so what” is that it’s useful to start thinking in terms of “how can Drush do this for me?” and you’ll often find that the answer is “pretty easily.”

Play a game with yourself. Next time you’re working on site building or anything that involves a lot of clicky clicky in the Drupal UI, give yourself a jellybean or a chip or something every time you do something in Drush instead of in the UI.

But why? Well for one, before you know it, you’ll be spending  much less time waiting on page loads. But secondly, Drush lends itself to automation, and thinking in terms of Drush naturally leads you to think in terms of automating and scripting things, which is a great place to be.

Practice some Drushful Thinking! And let me know any of your favorite Drush tips and tricks in the comments. Check out drushcommands.com for some more inspiration.

Make Your Product Vision Real – A Case for Incorporating Prototyping Into Your Next Project

As product designers and experience strategists, we research how people use systems and design products that tap into users’ natural behaviors. We want people to instinctively know how our product works.

Years of research into the human mind tells us that our brains love patterns, the repeated way in which something happens or is done. Our subconscious mind uses what we’ve learned from patterns – like turning a knob will open a door – to instinctively make decisions about what we do throughout our day. This is why we can walk or breathe without thinking about it – we spend most of our time running on autopilot.

We have an understanding of how people make decisions, but we forget to apply this knowledge when communicating our product vision to stakeholders.

There are Drawbacks to Designing in the Abstract

Experience design deliverables, or artifacts, are abstract. We too often produce artifacts, intended to build a shared understanding of a product vision, that are hard to understand. Low-fidelity wireframes and complex flow diagrams require stakeholders to think hard about what we are trying to communicate. They mentally fill in the gaps where we lack details. We consistently break Steve Krug’s number one rule: “Don’t make me think!”

Imagine how these abstract artifacts skew conversations about a product:

We show a stakeholder some wireframes and talk them through the features. Once they see them they begin to imagine the ways features will look and act based on similar products they have used.

While perfectly natural, this behavior is problematic – what we envision may be nothing like products this stakeholder has previously used. These assumptions your stakeholder makes will lead to you and your stakeholders having different expectations during product development.

You need to make artifacts as real as possible in order to elicit the most unbiased, unimpeachable feedback from users during research. You do not need to build a fully functioning product to validate your idea.You do need to eliminate or reduce the guesswork needed to understand how your product will work.

Make Your Product Vision Real

Prototyping is a great way to eliminate ambiguity so that you get the best results from user research. A prototype is a preliminary model of a product used to show a concept or validate an idea. A prototype should only contain the minimum amount of content, design and functionality needed to demonstrate how the end-product will function.

Context is key to determining fidelity of a prototype. If you are conducting user testing with a tech-savvy group of stakeholders, clickable wireframes may suffice. If you are introducing a new concept to a set of clients, then you may need a higher-fidelity, interactive web page. Your prototype should only contain the fidelity needed to have a meaningful conversation with your users about your product.

Build The Right Prototype For You

There are many different approaches to building prototypes. You can link wireframes together to show user flow with a system like inVision, or build interactive features using an open source CMS like Drupal.

When creating prototypes, make sure to include the following:

  1. The main actions that a user can take and the reactions they will receive from interactive elements.

  2. The key messages you want to communicate to users at different stages of their interaction.

  3. A programmatic way to track user behavior while they use the prototype.

Get Better Results from Your Projects

Some of the many benefits of prototyping are:

  • It produces more accurate results from user testing, allowing you to better determine what works and what doesn’t.

  • It gives you more opportunity to focus on interaction design by forcing you to have conversations about interactive elements during user research rather than development.

  • Prototypes bring less-apparent usability issues to light earlier in the development process.

  • You have a potential starting point to work from when beginning development, minimizing the amount of work that needs to be done in the long run.

John Whalen said “UX does not happen on a screen. It happens here. In the mind.” Keep that in mind (no pun intended) as you seek to build a shared understanding of, and validate, your product ideas. The more real you make the experience of interacting with your product early in the design process, the more accurate a feedback you will get from your users. For more thoughts on prototyping, check out Frederic Mitchell’s “Static Prototyping and Keeping Drupal Simple (KDS)” and “The Devil’s in The Details” by Sharon Smith!

Transitioning to Drupal 8 templates with Twig

As many of us know, Drupal 8 beta was released at the beginning of October which has given us a great preview of the goodies to come. One of those goodies is a new theme engine, Twig, which replaces PHPTemplate. Twig gives us a lot of extra power over our templates and allows us to clean up a lot of the extra cruft that PHPTemplate forced us to add.

So you may be asking, how will our brand new Drupal 8 templates look? Well they are going to be a lot leaner. The extra cruft of php tags, functions, and other miscellaneous bits are no longer needed – in fact, they don’t even work in Twig templates. Arguably, it will be easier to read at a glance what is happening in the Twig versions of Drupal templates. For a great example of how the new templates will look, we can crack open the Views module and compare the templates in the Views module 7.x version to the ones in the Views 8.x version. So let’s compare the views-view.tpl.php file from Views 7.x to views-view.html.twig file in Views 8.x.

Views-compare-part-oneViews-compare-part-two

Twig Comments

Starting from the top, lets work our way down to see what has changed. In the documentation section we can see that for the large block of comments, as well as single line comments, the {# #} syntax is used.

In the list of variables variables that are available to use, you may notice a few other changes. For example, Twig is not raw PHP, so the ‘$’ is not used at the beginning of variable names. Another change is that is that the $classes_array has been replaced by the attributes variable.

Rendering Variables

 Views-compare_example_one

Moving down to line #40 we can see the first instance of a variables rendered using Twig. The double curly bracket syntax, {{ my_variable }}, tells Twig that this is a variable and it needs to be rendered out. A variation of this syntax uses dot-notation to render variables contained in an array/object. This syntax looks like {{ my_variable.property_or_element }}, which makes it extremely easy to use. Dot notation is not used in this particular Twig template.

Twig Filters

Another powerful feature of Twig is template filters. Filters allow us to do simple manipulations of variables. The syntax for using a filter is similar to the syntax for rendering a variable. The difference is that after the variable name, you insert a | (pipe), followed by the name of the filter. For an example to make a string from a variable all lowercase you would do {{ variable_name|lower }} which transform all of the characters to lowercase. If you have used templating systems from other frameworks, such as Angular.js, this syntax may look familiar to you. This particular Views template does not use filters, but you can see examples of different filters on the Twig documentation site. If none of the predefined filters satisfy your requirements, you can extend Twig to create your own filter. The Twig documentation site provides details about creating your own custom filters..

Twig Logic

Views-compare_example_two

Jumping to line #42, we can see the {% %} (curly-bracket and percentage symbol) syntax, which is used for template logic, such as if statements. This syntax tells Twig that we are not rendering something, but rather that we need to process some logic, such as a control structure or loop, in our template.

The Takeaway

This blog post is a high level overview of how Twig templates in Drupal 8 will look.  With Twig, we can choose to use the out-of-the box tools it provides, or we can dive in and extend it with additional features such as new filters. For more information I would highly recommend reading through the Twig documentation for designers and for developers.

BADCamp Sprinting Success Story : Drush make files support YAML

After a very successful drush code-sprint at BADCamp 2014, drush make now supports YAML format!

Instead of the old INI format

YAML can be used with the latest version of Drush 7:

Included .make files whether local, or discovered recursively within downloaded projects, can be in either YAML of INI format.

In order to use the newly-supported YAML format, simply name files with a .yml extension, such as my_project.make.yml.

The best part? This can be used now! Even though YAML files are mostly a new concept for Drupal 8, drush make will parse YAML make files for Drupal 7, and even Drupal 6. Want to learn more about DRUSH make files? Check out Joe Turgeon’s “Getting Started With Grunt Drupal Tasks

AngularJS Meet Open Atrium

atrium-logo (1) The recent 2.23 version of Open Atrium contains a cool new interactive site builder and navigator application (see it in action). This application was written using the AngularJS framework.  The combination of Drupal, jQuery, and AngularJS proved to be powerful, but wasn’t without some pitfalls.

Using AngularJS in Drupal

AngularJS-large The basics of using Angular within Drupal is pretty straight-forward.  Simply reference the external AngularJS scripts using the drupal_add_js() function, then add your custom javascript app code, then use a tpl template to generate the markup including the normal Angular tags.  For example, here is the Drupal module code, javascript and template for a simple Angular app:

Now, obviously we aren’t using the full Angular framework here.  We aren’t using any directives, nor are we really using Angular as a MVC framework.  But it gives you the idea of how easy it is to get started playing with basic Angular functionality.

Angular plus jQuery

Developing javascript applications in Angular requires a different mindset from normal Drupal and jQuery development.  In jQuery you are often manipulating the DOM directly, whereas Angular is a full framework that allows data to be bound and manipulated on page elements.  Trying to combine both is often a source of frustration unless you understand more about how Angular works behind the scenes. Specifically, Angular has it’s own execution loop causing a mix of Angular and jQuery code to not seem to execute in a straightforward order.  For example, in the above code, we set the class of the H3 based on the current “count” variable.  What if we modified the updateCount function to try and set a css property for this class:

If you click the button you’ll notice that the css color does NOT change to red! The problem is that Angular is executing the query function call BEFORE it actually updates the page.  You need to delay the jQuery so it executes after the current Angular event loop is finished.  If you change the code to:

then it will work.  The timeout value can be anything greater than zero.  It just needs to be something to take the jQuery execution outside the Angular loop. Now, that was a horrid example!  You would never actually manipulate the css and class properties like this in a real application.  But it was a simple way to demonstrate some of the possible pitfalls waiting to trap you when mixing jQuery with Angular.

Drupal Behaviors

When doing javascript the “Drupal way”, you typically create a behavior “attach” handler.  Drupal executes all of the behaviors when the page is updated, passing the context of what part of the page has changed.  For example, in an Ajax update, the DOM that was updated by Ajax is passed as the context to all attached behavior functions. Angular doesn’t know anything about these behaviors.  When Angular updates something on the page, the behaviors are never called.  If you need something updated from a Drupal behavior, you need to call Drupal.attachBehaviors() directly.

Angular with CTools modals

In the Open Atrium site map, we have buttons for adding a New Space or New Section.  These are links to the Open Atrium Wizard module which wraps the normal Drupal node/add form into a CTools modal popup and groups the fields into “steps” that can be shown within vertical tabs.  This is used to provide a simpler content creation wizard for new users who don’t need to see the full node/all form, and yet still allows all modules that hook into this form via form_alters to work as expected. The tricky part of this is that as you navigate through the sitemap, Angular is updating the URLs of these “New” links.  But CTools creates a Drupal Ajax object for each link with the “ctools-use-modal” class in it’s Drupal behavior javascript.  This causes the URL of the first link to be cached.  When Angular updates the page and changes the link URLs, this Ajax object cache is not updated. To solve this within the Open Atrium Sitemap app, an event is called when the page is updated, and we update the cached Ajax object directly via the Drupal.ajax array. This was a rather kludgy way to handle it.  Ultimately it would be better to create a true Angular “Directive” that encapsulates the CTools modal requirements in a way that is more reusable.

Summary

Angular can be a very useful framework for building highly interactive front-ends.  Using Drupal as the backend is relatively straight-forward.  Angular allowed us to create a very cool and intuitive interface for navigating and creating content quickly within Open Atrium far easier than it would have been in jQuery alone.  In fact, we began the interactive site map tool in jQuery and the code quickly became unmanageable.  Adding functionality such as drag/drop for rearranging your spaces and sections would have been a mess in jQuery.  In Angular it was very straight-forward. Once you understand how Angular works, you’ll be able to blend the best of Drupal + jQuery + Angular into very rich interfaces.  Programming in Angular is very different.  Learn more about Angular on the Phase2 blog!