I need to put some JSON-LD content inside a script tag. Today, I’m put the content like this:
page_live.ex
defmodule ProjectWeb.PageLive do
use ProjectWeb, :live_view
@data_structure %{
"@context": "http://www.schema.org",
"@type": "WebSite",
name: "Project",
url: "https://project.com/"
}
@impl true
def mount(_params, _session, socket) do
socket = assign(socket, data_structure: @data_structure)
{:ok, socket}
end
end
root.html.leex
<!DOCTYPE html>
<html lang="pt-BR">
<head>
...
<%= if @data_structure do %>
<script type='application/ld+json'>
<%= Poison.encode!(@data_structure) %>
</script>
<% end %>
...
</head>
<body>
<%= @inner_content %>
</body>
<html>
The Poison lib always convert to String. I need a JSON.
How can I put the JSON content inside the script tag?
The trick is to use the raw
function to mark the encoded string as "safe" for use as JSON.
Assuming your controller is passing a map value to your view via something like:
def index(conn, _params) do
render(conn, "index.html", foo: %{x: "xray", y: "yep"})
end
Then you can do something like this (should be the same using Poison
):
<script>
var x = <%= @foo |> Jason.encode!() |> raw() %>;
console.log(x);
</script>