Back

MooseDog Studios

Here in Vermont, Convention Takes A Back Seat To Quality

MooseDog Studios Autumn Hero Picture

Integrating JSON-LD Into Your Eleventy Pages

Published: Jun 3, 2023
Updated: Apr 19, 2024

Well you ask excitedly, just what is this LD-JSON, and what can it do for me? For years, the major search engines, we mean primarily Google of course, have been trying to figure out a way to describe the unimaginable mountains of data they retrieve in indexing internet sites. There have been several different efforts at composing a language, or schema, that could be quickly integrated into a web page's HTML file. To wit: MicroData, RDFa, and finally the Google recommended JSON-LD

What they're looking for, and asking your help with, is what the ancient Greeks called meta-information, or information about the information. Known as more data (meta) about the existing data (your HTML file) in this instance.

This meta-data is referred to by an array of different names, such as "linked data", "structured data", "rich results", and Google bribes you to provide it to them with promises of improved SEO and SERP page presentations. And the "vocabulary" of this meta-data can get very obtuse very quickly.

It was an uphill struggle to be sure trying to understand this vocabulary, until I found this JSON-LD Playground. Copy the sample code below and paste it into their text area. Directly below that, click on the tab "Visualized", and a lightbulb should go on for you. It sure did for me. Whoever came up with this tool deserves a Nobel Prize for Data Visualization.

End result JSON-LD demo
{
    "@context":"https://schema.org",
    "@type":"Website",
    "name":"Selfless Studios",
    "description":"Web Development Where You Come First",
    "datePublished":"3/29/2023 - 3:16 PM",
    "dateModified":"5/10/2023 - 8:30 PM",
    "url":"https://mysite.com/",
    "logo":"https://mysite.com/img/mysite-logo.png",
    "contactPoint":
      {
        "@type":"ContactPoint",
        "name":"Sean McLovin",
        "email":"sean@mysite.com",
        "telephone":"+18421236521",
        "contactType":"Web Developer"
      }
    }

Note that the above code is nothing more than our familiar and friendly JSON and is what will, by the end of this article, be written directly into each page within your Eleventy generated site.

On To The Show

That JSON string posted above, so where did that come from? Follow along as we learn how Eleventy did that all by herself. Let's start with Eleventy's frontmatter, that configuration stuff at the top of all of your templates. I prefer to place the below data in all of my base layouts. Your data will differ of course. It's really quite simple:

/includes/layouts/base.njk
---
  eleventyComputed:
    meta:
      "@type": "Website"
      "name": "Selfless Studios"
      "description": "Web Development Where You Come First"
      # this must be hard coded as thus
      "datePublished": "2023-27-05"
      # this actually doesn't go in a base template, unless it's the only one you have
      # ideally place it in a more granular template for specific page/post types
      "dateModified": "{% lastModifiedSchemaShortCode page.inputPath %}"
      "url": "https://mysite.com{{ page.url }}"
      "logo": "https://mysite.com/img/mysite-logo.png"
      "contactPoint":
        "@type": "ContactPoint"
        "name": "Sean McLovin"
        "email": "sean@mysite.com"
        "telephone": "+18421236521"
        "contactType": "Web Developer"
  ---

Dates and URLs

I like to include some date and url information in this frontmatter, so it's included inside a Nunjucks double curly braces variable to be computed by Eleventy. In the code above, you will notice some extra data: "datePublished", "dateModified", and "url".

The "url" data comes straight from Eleventy's supplied data. The dates come to us through some....

Shortcode Magic

As you may have noticed, the "datePublished" has to be hand-written as it's otherwise impossible to know when the built file was uploaded/published to your server. The "dateModified" is a short code referencing your OS last modified data for a particular file. Here you go:

.eleventy.js
//
  // find the last modified file info to publish as 'dateModified' in schema data
  //
  eleventyConfig.addNunjucksShortcode("lastModifiedSchemaShortCode", function(fileNameWithPath) {

    // let's use Node JS to find all the file's OS specific meta-data
    let stats = fs.statSync(fileNameWithPath);

    // zero in on a date object
    let statsDate = stats.mtime;

    // and format said date object
    let formattedDate = `${statsDate.getUTCFullYear()}-${statsDate.getUTCMonth()+1}-${statsDate.getUTCDate()}`;

    return `${formattedDate}`;
  });

And finally, a shortcode to create the JSON-LD data in your 'head' element.

.eleventy.js
//
  // grab your custimized frontmatter from the "meta" object you've created in your template(s)
  // and inject it as a function parameter in your shortcode creator
  //

  eleventyConfig.addNunjucksShortcode("schemaDataShortCode", function(meta) {

    // the spread syntax for the win: https://gomakethings.com/the-spread-syntax-operator-in-vanilla-js/
    // to create a JS object you want, note the first line is included here as it must always be present in the final JSON

    let structuredData = {"@context": "https://schema.org", ...meta,};

    // send this off to be printed in your final HTML file
    // while simultainesly changing your JS object into valid JSON

    return `${JSON.stringify(structuredData)}`;
  });

And the last step, integrating JSON-LD into your HTML file, specifically in the 'head' element:

<script type="application/ld+json">
      {% schemaDataShortCode meta %} 
    </script>

And there you have it, structured data on every single page, specific to that page, generated by you and Eleventy.

So To Recap

TOP

SHARE