Including Image Styles with Your Drupal 8 Theme

Drupal 7 introduced the image styles system, and everyone who ever needed to deal with images in their content rejoiced. As a themer though, you can only ever rely on the presence of the three image styles that come with core. If you want to create a new blog post template that uses a non-core image style there are no easy ways to package that image style with your theme. And as such, it is hard for your theme to rely on an image style being present.

In order to pre-package image styles in Drupal 7 you need to implement the hook_image_default_styles() hook. Something that can only be done inside of a module. Meaning, if you want to bundle a set of image styles with your theme, your options are either write a module, or provide some instructions in a README that explains that someone needs to create a specific image style with a specific name. Neither of which are ideal.

During DrupalCon Amsterdam I attended a session that covered many of the changes to the theme layer in Drupal 8. There are lot of really great things coming. Towards the end, one of the presenters mentioned that Drupal 8 now allowed for the inclusion of exported image styles directly in a theme. He didn't go into much detail other than that, but my curiosity was piqued. When I started looking more into how this worked I discovered there wasn't any documentation yet. So I ended up spending few hours poking around, and figuring out how to do it, and then writing up some documentation for the Drupal.org Handbook.

How This Works

Drupal 8 resolves this issue by allowing image styles to be exported, and included within a theme, using the new configuration management tools. When the theme is enabled any image styles included with the theme are loaded into the active configuration and immediately made available for use. Sound awesome? That's because it is. And it's also really easy to do.

  1. Create the Image Style you wish to include using the UI.
  2. Export the Image Style as YAML using Configuration management.
  3. Include the exported YAML in the config/install directory of your theme, following the appropriate naming convention.

This video demonstrates the process of exporting an image style and including it in your Drupal 8 theme.

Comments

Add new comment

Filtered HTML

  • Web page addresses and email addresses turn into links automatically.
  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <code class> <ul type> <ol start type> <li> <dl> <dt> <dd><h3 id> <p>
  • Lines and paragraphs break automatically.

About us

Drupalize.Me is the best resource for learning Drupal online. We have an extensive library covering multiple versions of Drupal and we are the most accurate and up-to-date Drupal resource. Learn more