N
Nuxtβ€’2y ago
TimKern

render:html hook in defineNitroPlugin duplicates the whole page content

i am writing a plugin for a "table of content" component so i can get all headings for it. i am using the render:html hook to manipulate the html. After manipulating the html the page will show me the whole server side rendered page and beneath it shows me the whole server side rendered page πŸ˜“ here is the plugin code. am i using the hook wrong πŸ€”
import { parse } from 'node-html-parser'

export default defineNitroPlugin((nitroApp) => {
nitroApp.hooks.hook('render:html', (html, { event }) => {
html.body = html.body.map((chunk) => {
const d = parse(chunk)
const tocContainer = d.querySelectorAll('.toc-list')
if (!tocContainer.length) {
return
}
const headings = d.querySelectorAll(
':is(h1,h2,h3,h4,h5,h6)'
)
headings.forEach((heading) => {
const text = heading.textContent || heading.innerText
if (!heading.id && !heading.attributes.id) {
const id = text
.toLowerCase()
.replace(/[^a-z0-9 ]/g, '')
.replace(/\s/g, '-')
.replace(/^-*|-*$/g, '')
heading.setAttribute('id', id)
tocContainer.forEach((toc) => {
toc.appendChild(
parse(
`<li class="toc-${heading.rawTagName}"><a href="#${id}">${text}</a></li>`
)
)
})
} else {
tocContainer.forEach((toc) => {
toc.appendChild(
parse(
`<li class="${heading.rawTagName}"><a href="#${
heading.id || heading.attributes.id
}">${text}</a></li>`
)
)
})
}
})
return d.toString()
})
})
})
import { parse } from 'node-html-parser'

export default defineNitroPlugin((nitroApp) => {
nitroApp.hooks.hook('render:html', (html, { event }) => {
html.body = html.body.map((chunk) => {
const d = parse(chunk)
const tocContainer = d.querySelectorAll('.toc-list')
if (!tocContainer.length) {
return
}
const headings = d.querySelectorAll(
':is(h1,h2,h3,h4,h5,h6)'
)
headings.forEach((heading) => {
const text = heading.textContent || heading.innerText
if (!heading.id && !heading.attributes.id) {
const id = text
.toLowerCase()
.replace(/[^a-z0-9 ]/g, '')
.replace(/\s/g, '-')
.replace(/^-*|-*$/g, '')
heading.setAttribute('id', id)
tocContainer.forEach((toc) => {
toc.appendChild(
parse(
`<li class="toc-${heading.rawTagName}"><a href="#${id}">${text}</a></li>`
)
)
})
} else {
tocContainer.forEach((toc) => {
toc.appendChild(
parse(
`<li class="${heading.rawTagName}"><a href="#${
heading.id || heading.attributes.id
}">${text}</a></li>`
)
)
})
}
})
return d.toString()
})
})
})
0 Replies
No replies yetBe the first to reply to this messageJoin
Want results from more Discord servers?
Add your server