'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
Solution 1:[1]
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>
pathprop is the directory name of the blog post prefixed with a slash (eg: /blog1)srcprop 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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | UdithIshara |
