ConstanceHermit
ConstanceHermit

Reputation: 1

Nuxt Content: how to fetch markdown content and insert into a static page?

Some Context

I'm building a blog, with content mostly coming from markdown files, using NuxtJS Content.
It if helps, you can see my project on Github (or the deployed site here).

I understand how to create dynamic pages from the MD files under /content.
But I don't know how to inject content from one of these files into a static page.

content/
├── blog/
│   ├── post1.md
│   ├── post2.md
├── privacy/
│   ├── policy.md
│   └── something-else.md
pages/
├── blog/
│   ├── _slug.vue
├── privacy/
│   ├── _slug.vue
├── privacy.vue
├── index.vue

Using my current method/knowledge, I generated a dynamic page based on policy.md:

<template>
    <article>
      <nuxt-content :document="policy" />
    </article>
</template>

<script>
export default {
  async asyncData({ $content, params }) {
    const policy = await $content('privacy', params.slug).fetch()
    return { policy }
  }
}
</script>

But I don't want to generate a dynamic page from the MD, or use the slug in the route.
I want to take the contents of policy.md, and insert them into privacy.vue - but I don't know how.

What I tried

It doesn't work using the method from above, but I feel like it should.

console.log(policy) returns [object] [OBJECT]
& console.log(policy.title) returns undefined What should this tell me? (trying to improve my debugging skills here lol)

Why does this work in _slug.vue but not in page.vue?
Feel like I'm missing some contextual knowledge re: how things work / what the right approach is here.

Upvotes: 0

Views: 942

Answers (1)

ConstanceHermit
ConstanceHermit

Reputation: 1

Alright, so I solved my own problem just before hitting submit by adding this to the static page template:

<div v-for="policy in policy" :key="policy.title">

Why did that work?

Is it because asyncData doesn't know in advance how many items will be fetched, and creates an array -> so policy.title was undefined when it wasn't policy.title at position X in the array (which, I guess, the v-for gives us?)..

I thought that giving a path to a file rather than a dir, like:

const policy = await $content('privacy/policy.md', params.slug).fetch()

Would make it clear that it would be a single item, but that didn't work for me when I tried it earlier. How does that work?

I think this is probably not a nice way to fix it. I mean, I know that there will only ever be one file in this dir, but yeah, there must be a more appropriate way to do this?

Upvotes: 0

Related Questions