Skip to content

Instantly share code, notes, and snippets.

@ashx3s
Last active November 19, 2021 16:33
Show Gist options
  • Select an option

  • Save ashx3s/0c457082cdf9c19d5e223be5acf3084a to your computer and use it in GitHub Desktop.

Select an option

Save ashx3s/0c457082cdf9c19d5e223be5acf3084a to your computer and use it in GitHub Desktop.
Render Nuxt Content

Nuxt Content Render CMS Content

Render your blog articles dynamically

To actually render your pages, you will create a slug file that is used to render all the content.

  • Create a pages/_slug.vue file
    • This will be used to create the template

Script Tag

<script>
export default {
async asyncData({ $content, params, error }) {
    try {
      const post = await $content(`blog/${params.slug}`).fetch()
      return {
        post,
      }
    } catch (e) {
      error('No article found')
    }
  }
</script>

Deconstructing this syntax

  • The try catch statement is used for error handling
  • If you use a try/catch, make sure the return statement is inside the try
  • In the string $content(blog/${params.slug}), you are specifying:
    • content directory: $content()
    • the blog directory: blog/
    • the relevant post url ${params.slug}
  • This is using template literal syntax to dynamically generate the url string
  • The .fetch() method is used to retrieve the post

Template Tag

<template>
  <article>
    <h2>{{ post.title }}</h2>
    <nuxt-content :document="post">
  </article>
</template>
  • This is a very simple template.
    • The script tag calls in all the information from the content directory. It gives you access to all the fields in the collection used to make the article.
    • using the v-bind on :document will send the data from the post to the nuxt-content tag, thus rendering all the information in it.
  • You can call information from other fields with mustache syntax as done above

Displaying Content

  • To display a markdown file's main content, use the syntax:
<nuxt-content :document="post">
  • remember that post needs to be set to whatever you return your data as in your script
  • To display any of the frontmatter content, you will use mustache syntax and select the object
    • ie: for the post's title, use <h2>{{ post.title }}</h2>
      • This will work because the title is just a string, so it does not need to compile anything
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment