If you happen to’re studying this, you’ve come throughout a necessity that almost all Opti builders encounter of their careers; You want to appropriately show a vector picture format (SVGs and the like). The <IMG> tag simply isn’t going to chop it anymore. Posts like this are a right-of-passage for Opti bloggers.
“So,” you suppose, “if there are such a lot of different blogs on the subject, why ought to I learn yours?” Firstly, you get pleasure from my acquainted and conversational tone of writing.
Cary Elwes does the English accent, and I do the nerd stuff.
Second, you’ve already come this far; you would possibly as effectively end at this level; it’s not lengthy, I promise. To that time, and most significantly, I’ve seen some advanced options on the market. This one is a fast and easy implementation. 100% Assure!
The VectorFile Class
[MediaDescriptor(ExtensionString = “svg”)]
public class VectorFile : ImageData
{
public override Blob Thumbnail { get => BinaryData; }
public digital string XML
{
get
{
strive
{
var blob = BinaryData;
var xmlDoc = new XmlDocument();
xmlDoc.Load(blob.OpenRead());
return xmlDoc.InnerXml;
}
catch
{
return “”;
}
}
}
}
This pleasant little class will extract the thumbnail for previews and place the picture in an XML doc that may be inserted right into a view as a <SVG> tag. You’ll be able to see from the MediaDescriptor attribute that we’re solely permitting .SVG recordsdata right here. This checklist could be expanded as wanted. That is the place it’s also possible to provide totally different properties relating to your SVG within the class; it’s simply content material!
The VectorFileController Class
public class VectorFileController : AsyncPartialContentComponent<VectorFile>
{
protected override async Process<IViewComponentResult> InvokeComponentAsync(VectorFile currentBlock)
{
return await Process.FromResult(View(“~/Options/Media/_vectorFile.cshtml”, currentBlock));
}
}
This could look acquainted to CMS12 block growth, simply your run-of-the-mill controller. No tips, no fills.
The VectorFile View
@mannequin VectorFile
@if (Mannequin != null)
{
@((MarkupString)Mannequin.XML)
}
Many devs would have you ever use @Html.Uncooked to place the SVG code on the display screen, however with the MarkupString struct. We’re on much less shaky floor right here as a result of MarkupString is parsed in an HTML or SVG format somewhat than trusting that the foolish SVG you grabbed off Pinterest for that firm social gathering doesn’t have some nasty embedded code.
Now, on the subsequent add to your Media folder, any SVG file ought to seem as a VectorFile as an alternative of an ImageFile! (You probably did take the .svg extension out of the MediaDescriptor of your raster picture class, proper?)
Informed you it will be quick and easy! Pleased coding Opti-mists!