jamckp
jamckp

Reputation: 207

Treat SVG as an image in Silverstripe

I'm trying to upload images in Silverstripe and have them treated as images rather than a document link.

I've added SVG to the allowed filetypes and can upload an SVG file but when I hit insert the editor inserts the tag as

<a href="/assets/uploads/somefile.svg">somefile.svg</a>

I would like to treat SVG as any other image format where inserting will insert the tag as a regular image

<img src="/assets/uploads/somefile.svg">

What is the best way to achieve this?

Upvotes: 3

Views: 2334

Answers (3)

MicSck
MicSck

Reputation: 11

I've written a SilverStripe module to do exactly that (treat SVG as image instead of file): https://github.com/micschk/silverstripe-svg-images/

See the README for general pointers on how to set up SVG-as-image if you don't want to require the module.

Upvotes: 0

in SS3 just use this in your config.yml:

File:
    allowed_extensions:
        - svg
Image:
    allowed_extensions:
        - svg

Upvotes: 1

Turnerj
Turnerj

Reputation: 4278

After debugging around HtmlEditorField.js, I found that the issue for SVGs not displaying was that the "Insert Media" screen's upload field does not consider an SVG as an image. (I originally thought the problem was TinyMCE but that wasn't the case)

I knew that the File class has a static property called app_categories which contains things like all the extensions SS thinks are images. By default, SVG is not in this list.

In Silverstripe 3.1, if you specify the following, it will add SVG to the "image" category:

$categories = File::config()->app_categories;
$categories['image'][] = 'svg';
File::config()->app_categories = $categories;

Alternatively as a YAML config:

File:
  app_categories:
    image: 
      - svg

That simple change was enough for the file upload on the "Insert Media" screen to correctly treat a SVG as an image which in turn triggered the right entwine function to use the <img> tag rather than an anchor.

While this method solves your specific issue, there could be side effects throughout other parts in Silverstripe for adding SVG to the image app category.

One additional thing, I needed to update my .htaccess file in my assets folder for it to allow viewing of SVG files otherwise I got a 403 Forbidden error.

Upvotes: 6

Related Questions