Blog

Coding, Smart Home, other tech stuff

How this blog works under the hood - Part 2

Using the Content plugin to render markdown

In my previous post it told you about using Nuxt 3 for creating statically rendered pages at build-time was my way to go.

I didn't want to write lots of HTML code when writing a blog post. I want to be able to focus on writing good articles. This is why I decied to use Markdown for authoring my content.

But how do you render Markdown on a webpage? The answer is relatively simple: using a Nuxt plugin called Content. This plugin allows you to render different types of content like Markdown, JSON, YAML or CSV as HTML.

To start, you simply need to install the package:

$ npm install @nuxt/content

After installing the plugin, don't forget to include it in your nuxt.config.ts:

export default defineNuxtConfig({
    // snip
    modules: [
        '@nuxt/content'
    ]
    // snip
})

You can then continue to create a folder named content inside your project directory. Inside this folder you can simply place your Markdown files and Nuxt offers an easy way to display the content on your page. Have a look at their documentation to get a feeling about how flexible the content plugin is and what it can do for you.

I chose the approach of using the queryContent() function to have more control over where to place my content. The page used to display this blog post for example, looks similar to this:

<template>
    <div>
        <ContentRenderer :value="data" />
    </div>
</template>

<script lang="ts" setup>
const { params } = useRoute()
const { data } = await useAsyncData(`post-${params.slug}`, () => {
    return queryContent('posts').where({ slug: params.slug[0] }).findOne()
})
</script>

I am using queryContent to look for content inside the subfolder posts that match the yaml-frontmatter property called slug. This gives you an object that contains the parsed Markdown content as well as the frontmatter defined in your file. The <ContentRenderer> componet is used to display the parsed content.

Like what you are reading?

© strauss.co.at 2024