How to inject HTML/manipulate DOM with variable in Phoenix (Elixir) rendering for example to dynamically insert an SVG or PNG?

Viewed 509

If I have some svg passed through assign to the view on say an svg variable, I can render into the view with:

<%= @svg %>

However, in the DOM I can inspect the page and see intelligently phoenix has default to not rendering the SVG, as it's a string representation. However, I can't figure out how to override that default so that I can inject into the dom/render the SVG properly and not just show the string in the page, but actually render the image. How would I do this? Do I have to use javascript to render after the fact—that's okay too but it would be really nice to just server side render.

Thank so much!

1 Answers

So that the content is not escaped, you can use the Phoenix.HTML.raw/1 function.

Here is an example of SVG QRCode generation:

<section>
  <p style="text-align:center">
    <%=
      Routes.some_path(MyApp.Endpoint, :index, @some_id)
      |> QRCode.create!(:high)
      |> QRCode.Svg.create()
      |> raw()
    %>
  </p>
</section>

which produces inline SVG. Note that the raw/1 function is automatically imported in templates.

Related