Metadata

A guide to definining page metadata for reuse across pages.

By default, pages support the powerful export ES module syntax:

export const date = Date.parse("2022-01-01T00:00:00")
export const title = "Daily post " + date.toLocaleDateString()
export const meta = { date, title }

# {meta.title}

This allows your to create arbitrary variables and expressions, and use them inside your page. It also exposes them to other pages, which can import them via import statements:

import { title } from "@pages/post-1"

Page title: {title}

Frontmatter

In addition to exports, pages also come with support for YAML frontmatters, using the remark-frontmatter plugin. Start your page with a section in YAML format, delimited by three dashes ---:

---
title: Hello, frontmatter!
---

# {frontmatter.title}

As hinted at in the above, the frontmatter data is accessible within the page via an object named frontmatter. In other pages, the frontmatter data is accessible via an exported variable named meta, to keep the consistency with the ES version described in the previous section:

import { meta } from "@pages/post-2"

Page title: {meta.title}

Exposing metadata to templates

One important use case for metadata is exposing data to templates. Templates allow you to wrap your page in a component, so that designs can be reused across multiple pages without duplication. In addition to the page content, the template has access to the meta variable of your page, if it is defined.

export const Template = ({ children, meta }) => {
  return (
    <>
      <h1>{meta?.title}</h1>
      <hr />
      <div>{children}</div>
    </>
  )
}

As noted above, the meta variable can be either a variable defined explicitly in JavaScript with the export keyword:

export const meta = {
  title: "My JS title",
  date: Date.parse("2022-01-01T00:00:00"),
}

or the content of the YAML frontmatter:

---
title: "My frontmatter title",
date: "January 2022, 01"
---

Notice that if you are using the YAML frontmatter syntax, you will not be able to use JS expressions. Only primitive types, such as strings and numbers, are supported.

© 2022 Motif Land Inc. All rights reserved. This site is built with Motif.