Published in Development
How To Add Structured Data (JSON-LD) to Hugo

How To Add Structured Data (JSON-LD) to Hugo

Prevent Hugo from adding backslashes to the URLs in your structured data.

The issue is Hugo is automatically escaping the JSON data when you encapsulate it in the script block. No combination of printf, safeHTML, or safeJS on the individual data will stop Hugo from reformating the data.

To prevent Hugo from reformating the data, you need to build the JSON structured data—make sure to format the data correctly—manually in a scratchpad. Then, use a printf statement to output the HTML directly to bypass Hugo.

{{- $jsonld := newScratch -}}
{{- $jsonld.Set "@type" "WebSite" -}}
{{- $jsonld.Set "@id" (printf "%s#website" site.BaseURL) -}}
{{- $jsonld.Set "url" site.BaseURL -}}
{{- $jsonld.Set "name" site.Title -}}
{{- $jsonld.Set "description" site.Home.Description -}}
{{- $jsonld.Set "inLanguage" "en-US" -}}
{{ printf `<script type="application/ld+json">%s</script>` ($jsonld | jsonify) | safeHTML }}

The above is a workaround until Hugo adds a directive that allows you to bypass the auto-formatting.

I hope this helps anyone that is running into this issue.

Happy Coding!


comments powered by Disqus