Skip to content

Instantly share code, notes, and snippets.

@codeflorist
Last active March 17, 2023 10:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codeflorist/aad1313643f2a529f34b7b81b0b865f8 to your computer and use it in GitHub Desktop.
Save codeflorist/aad1313643f2a529f34b7b81b0b865f8 to your computer and use it in GitHub Desktop.
Nuxt 3 Plugin providing directives and helpers to convert line breaks to <br>, <p> or arrays.
/*
Nuxt 3 Plugin providing directives and helpers
to convert line breaks to <br>, <p> or arrays.
---------------------------------------------
Usage as directives (WARNING: can lead to XSS attack!):
<div v-nl2br="string" />
<div v-nl2p="string" />
Usage as helper in script setup:
const { $nl2array, $nl2br, $nl2p } = useNuxtApp()
const array = $nl2array(string)
Usage as helper in template:
<p v-for="(p,key) in $nl2array(string)" :key="key">{{ p }}</p>
*/
export default defineNuxtPlugin((nuxtApp) => {
const nl2array = (string: string): Array<string> => {
return string.split(/\r?\n/)
}
const nl2br = (string: string) => {
return nl2array(string).join('<br />')
}
const nl2p = (string: string) => {
return '<p>' + nl2array(string).join('</p><p>') + '</p>'
}
nuxtApp.vueApp.directive('nl2br', (el, binding) => {
el.innerHTML = nl2br(binding.value)
})
nuxtApp.vueApp.directive('nl2p', (el, binding) => {
el.innerHTML = nl2p(binding.value)
})
return {
provide: {
nl2array,
nl2br,
nl2p,
},
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment