Third & GroveThird & Grove
Dec 2, 2016 - Abby Milberg

SVG Images in Drupal 8

Although many websites today use vector graphics, Drupal doesn't provide support for SVG images out of the box. With a bit of customization, however, displaying SVGs on your site can be easy.

Since Drupal's image field type won't let you add "svg" as an allowed extension, we're going to use a file field instead. Create a new file field, set "svg" as the only allowed file extension, and enable the "Description" field, which we will use to provide alt text for the image. Then, in your content type's display settings, make sure that the field's display format is set as "Generic file."

Next, it's time for a bit of code. All of Drupal's normal image rendering functions throw errors when given an SVG file, so we're simply going to pull out the file's URL and description text as variables and place them into an img tag ourselves. The following preprocess function pulls out said variables and passes them to the field's template:

/**
 * Implements theme_preprocess_field().
 */
function your_theme_name_preprocess_field(&$vars, $hook) {
  if ($vars['field_name'] == 'field_your_field_name') {
    $img_path = $vars['items']['0']['content']['#file']->url();
    $alt_text = '';
    $alt_text = $vars['items']['0']['content']['#description'];
    $vars['img_path'] = $img_path;
    $vars['alt_text'] = $alt_text;
  }
}

 

Note that we set the alt text as blank before assigning its value, since the Description field is optional. This also ensures that there is an alt tag present even if the user doesn't provide a description, which is recommended for accessibility purposes.

 

Next, we grab those variables in the field's template, which will follow the naming convention field--field-your-field-name.html.twig.

<img src="{{ img_path }}" alt="{{ alt_text }}" />

 

Clear your caches, and just like that you should have a working SVG image field on your site!