Search code examples
svgrazorblazorblazor-server-side

Is it possible to load a razor component from a string and use it inside Blazor page?


I want to dynamically load SVG from string and use it inside Blazor page. Because I want to use parameters of this svg, so I think svg should be inside a razor component, for example:

<svg>
<circle cx="150" cy="150" r="@Radius" stroke="black" stroke-width="3" fill="@BackColor" />
</svg>
@code {
    [Parameter]
    public double Radius { get; set; }
    [Parameter]
    public string BackColor { get; set; }
}

I would like to load such a component above from a string (from database or from uploaded file, it doesn't matter) and render it in my page and use its parameters. Is it possible to do it ?

I tried to use DynamicComponent, but DynamicComponent requires to provide a known type of component, but inside a project the type is not known, I have only a content loaded from external source.


Solution

  • You can show an SVG string by casting it to a MarkupString.

      @((MarkupString)svgText)
    

    But that won't process the @BackColor. You could do your own replacements, either with strings, RegEx or XElement.