JSON+LD Example for Hugo Static Sites

hugo in json tags

After making a few sites with Hugo recently and each time having to work out a good way of building a JSON+LD structure, I thought I’d blog about it. In this post we’ll share the structure that I use within the head element of the html document. It can be just put within the <head> element, or even better when using Hugo is to make it into it’s own partial file.

The code is split into two, one being for the individual blog posts and the other being for the home page and other, non-post pages. This is mainly because they have a different @type in the schema.

Needed Parameters:

Name Description
.Params.featured_image (optional) The social media or headline image for this post.
.Params.tags (optional) keyword tags for the blog post to list as a csv
.Params.Author The authors name, found on each post
.Description for non blog posts, add a description for the page
<script type="application/ld+json">
  {{ if .IsPage }}{
    "@context": "http://schema.org",
    "@type": "BlogPosting",
    "mainEntityOfPage": {
        "@type": "WebPage",
        "@id": "{{ .Site.BaseURL }}"
    },
    "articleSection": "{{ .Section }}",
    "name": {{ .Title }},
    "headline": {{ .Title }},
    "description": {{ replace .Summary "\n" " " }},
    {{ if .Params.featured_image }}"image": {{ .Params.featured_image }},{{ end }}
    "inLanguage": "en-GB",
    "author": {
      "@type": "Person",
      "name": {{ .Params.Author }}
    },
    "creator": {{ .Params.Author }},
    "publisher": {
        "@type": "Organization",
         "name": {{ .Site.Title }},
        "logo": {
            "@type": "ImageObject",
            "width": "192",
            "height": "192",
            "url": "<< your logo url >>"
        }
    },
    "copyrightYear": "{{ .Date.Format "2006" }}",
    "datePublished": {{ (time .Date).Format "2006-01-02T15:04:05Z" }},
    "dateModified": {{ (time .Date).Format "2006-01-02T15:04:05Z" }},
    "url": {{ .Permalink }},
    "wordCount": {{ .WordCount }},
    "keywords": {{ if .Params.tags }}{{ delimit .Params.tags "," }}{{else}}""{{ end }}
  }{{ else }}{ 
    "@context": "http://schema.org", 
    "@type": "WebSite", 
    "url": {{ .Permalink }},
    "name": {{ .Title }},
    "author": {
      "@type": "Person",
      "name": {{ .Site.Title }}
    },
    "description": "{{ if .IsHome }}{{ htmlEscape .Site.Params.description }}{{ else }}{{ htmlEscape .Description }}{{ end }}"
  }{{ end }}
</script>

Parse Errors#

If you are like me and start getting messages like this from the stuctured data tester:

\x26rsquo; bad escape sequence in string for JSON-LD

It might be because the line you have like "name": "{{ .Title }}" is wrapped in quotes. Take these off and it should work. So the end result would look more like this: "name": {{ .Title }}.