Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save SebbeJohansson/99aa4f1f622552d29927c208c528b489 to your computer and use it in GitHub Desktop.
Save SebbeJohansson/99aa4f1f622552d29927c208c528b489 to your computer and use it in GitHub Desktop.
Storyblok Richtext Link Correction for Nuxt2 (storyblok adds a language automatically at the start of the url that we dont use)
<script>
import { mapState } from 'vuex';
import { renderStoryblokRichText } from '~/utils/storyblok/rich-text-helpers';
export default {
props: {
blok: {
type: Object,
required: true,
},
raw: {
type: Object,
required: false,
default: null,
},
},
computed: {
text() {
return renderStoryblokRichText(this.blok.text, this.rootPath);
},
css() {
const css = {};
if (this.blok.text_color?.color && this.blok.text_color?.color !== '') {
css.color = this.blok.text_color.color;
}
return css;
},
classes() {
const classes = [];
if (this.blok.text_align) {
classes.push(`sb-text-line--text-align-${this.blok.text_align}`);
}
return classes;
},
...mapState({
rootPath: (state) => state.litium.channel.rootPath,
}),
},
};
</script>
<template>
<div v-editable="blok" class="sb-text-line" :class="classes" :style="css">
<div class="sb-text-line__content" v-html="text" />
</div>
</template>
<style>
.sb-text-line--text-align-right {
text-align: right;
}
.sb-text-line--text-align-left {
text-align: left;
}
.sb-text-line--text-align-center {
text-align: center;
}
.sb-text-line__content *:first-child {
margin-top: 0;
}
.sb-text-line__content *:last-child {
margin-bottom: 0;
}
</style>
import { renderRichText } from '@storyblok/nuxt-2';
import { makeLinkAbsolute } from '~/utils/storyblok/link-helpers';
export const renderStoryblokRichText = (richText, channelRootPath) => {
const richTextJson = JSON.stringify(richText);
const richTextObject = JSON.parse(richTextJson);
const loopThroughNodes = (node) => {
const localNode = { ...node };
localNode.content.map((content) => {
if (content.content) {
content = loopThroughNodes(content);
}
if (content.marks) {
content.marks.map((mark) => {
if (mark.type === 'link' && mark.attrs?.href) {
mark.attrs.href =
makeLinkAbsolute(mark.attrs.story?.full_slug, channelRootPath) ??
mark.attrs.story?.url ??
mark.attrs.href;
}
return mark;
});
}
return content;
});
return localNode;
};
const rendered = renderRichText(loopThroughNodes(richTextObject));
return rendered;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment