Drupal 8 and SVG images
Back in January I worked on a Drupal 8 project. And I needed to use SVG images across multiple content types. Only problem was that Drupal 8 doesn't support SVG images out of the box. So, I had a choice, not use beautiful and scalable SVG images at all or find a solution. Being a Drupal developer and passionate about programming, of course I choose the second option. After I completed module development, I decided that I will share it with the community. Ten months later, SVG Formatter is used on more than 1100 Drupal 8 sites. I'm really proud of this.
Now, let's see how to use it.
You can install the module in 3 ways: manual installation, installation with drush or composer. If you are really really old school or you just don't have SSH access to your Drupal instance then you have to use manual installation. Head over to https://www.drupal.org/project/svg_formatter copy download link and paste it the appropriate field on the modules installation page. To install it with Composer or Drush use one of the following commands:
composer require drupal/svg_formatter
drush en svg_formatter -y
After you installed the module, you can start using it. The most important thing to understand is that SVG Formatter as the name suggest is a field formatter. It does not add a new field type to Drupal. It just acts as a formatter for the standard File field. You cannot upload SVG image in standard image field. Only allowed file extensions for an image field are: png gif jpg jpeg.
So, in order to display SVG images first thing you have to do is to add a File field to your entity type. You can add it to a node, taxonomy term, user or to any fieldable content entity type.
Please remember to add svg to the allowed extensions list.
After you created the File field go to the Manage display tab for your entity (in our case that is Article content type). Here you will see the standard form. You can see all fields listed, with Field, Label and Format columns. Change format option for your file field to SVG Formatter.
By inlining SVG image you will also reduce page load time, because your browser won't have to make an additional HTTP request to retrieve the image. So, that is additional benefit. Downside is that browser won't be able to cache inline images, so choose wisely between inline and not inline images.
You can also set image dimensions, and enable/disable alt and title attributes. Since File fields don't have these attributes, their values are automatically generated from the image filename. That means that you cannot enter alt and title values the way you can in the Image field type.
Like any other field, you can render this field (with SVG formatter) programmatically. Let's say that you have a settings form and that you want to programmatically render the image. You can do it like this:
use Drupal\node\Entity\Node; $node_id = 1; // Some node ID. $form['svg_image'] = Node::load($node_id)->field_svg_image->view('default');