RmR
RmR

Reputation: 2303

NUXT: displaying images using Markdown-it relative to markdown content

This is for a pure static implementation of Nuxt. I am using markdown content that is read from a yaml content file (not markdown). Since the content is in json objects, they are being rendered using $md.render(blog.content). Assume that blog.content is a markdown string.

The template is as follows:

...
<div v-html="$md.render(blog.content)></div>
...

The nuxt.config.js file has the following:

export default {
  target: static,
  ...
  modules: [
    '@nuxt/content',
    '@nuxtjs/markdownit',
    ...
  ],

  markdownit: {
    runtime: true,
    html: true,
  },
  ...
}

This works as expected for regular md strings.

I would like to use an image stored in the images subdirectory of the blog page (not from assets or static directory). And refer to it in the markdown string

The structure of the content directory is:

content
   blogs
      blog1
         images
            b1i1.png
            b1i2.png
         content.yaml
      blog2
         images
         content.yaml
   ...

The markdown string could be something like this

# Study this Digaram
The following is a diagram

<img src="images/b1i1" alt="diagram"/>

It there a way to send this image for vue to resolve it to the path of the generated image? Thanks

Upvotes: 0

Views: 1025

Answers (2)

Dave Stewart
Dave Stewart

Reputation: 2534

As of Nuxt 3, you can use the nuxt-content-assets module.

At run time, it copies all images found in content sources to a build-time folder, replaces any matching relative paths with public ones, and serves the images using Nitro.

At build time, images are copied to the final build output.

Upvotes: 0

UdithIshara
UdithIshara

Reputation: 425

By default Nuxt content looks for the images stored under "statics" directory. If you want to access images from a different place than that (IE blogs/slug/images)

You'll have to "require" them manually or use a custom component for that, something like below

src/components/VImg.vue

<template>
  <img :src="imgSrc()" :alt="alt" />
</template>

<script>
export default {
  props: {
    src: {
      type: String,
      required: true,
    },
    alt: {
      type: String,
      required: true,
    },
    path: {
      type: String,
      required: true,
    },
  },
  methods: {
    imgSrc() {
      try {
        return require(`~/content${this.path}/images/${this.src}`)
      } catch (error) {
        return null
      }
    },
  },
}
</script>
  • path prop is the directory name of the blog post prefixed with a slash (eg: /blog1)
  • src prop is the image name (eg: b1i1.png)

Then use this instead of an <img/> tag in your blog _id file (make sure to change require(~/content${this.path}/img/${this.src}) according to your project structure)

Upvotes: 0

Related Questions