【问题标题】:Contentful API: How to render entry-hyperlink内容 API:如何呈现入口超链接
【发布时间】:2021-08-31 03:45:48
【问题描述】:

我正在尝试使用 rich-text-html-renderer 将 Contentful Document 呈现为 html。但是,如果富文本包含 entry-hyperlink 类型的节点,则呈现如下: <span>type: entry-hyperlink id: QUfIK1T2dFDnubS5Ztc9N</span>

根据文档,您需要将选项对象传递给documentToHtmlString。 但是如何在此渲染方法中进行异步调用以获取此 id 的实际 Contentful 条目?

就我而言,我试图在 Nuxt 环境中的 Vue 组件中执行此操作。

【问题讨论】:

  • 不确定这里有什么问题。您不确定如何在 Nuxt 中编写异步调用,或者您已经编写的某些代码未按预期呈现?
  • @kissu 我正在尝试使用内部链接呈现富文本。看来我需要在渲染选项中加载目标异步。或者我误解了一些概念......
  • 你能告诉我们你到目前为止做了什么吗?它还可以帮助我了解问题所在,因为我不确定在这里要调用什么。你已经读过这个了吗? contentful.com/developers/docs/javascript/tutorials/…

标签: nuxt.js contentful


【解决方案1】:

在进一步挖掘文档后,我发现了缺失的链接: 我需要再次在富文本组件中加载内容条目,而不仅仅是依赖父条目。 父条目加载了这个看起来很完整的富文本条目,但如果我在我的组件中加载它,它会加载更多内容,并且这个 entry-hyperlink 节点包含我呈现链接所需的所有信息。
这里是我的富文本 vue 组件:

<template>
    <!-- eslint-disable-next-line vue/no-v-html -->
    <div class="text" v-html="html"></div>
</template>
<script lang="ts">
import { computed, defineComponent, useAsync } from '@nuxtjs/composition-api';
import { Block, INLINES, Inline } from '@contentful/rich-text-types';
import {
    documentToHtmlString,
    Options,
} from '@contentful/rich-text-html-renderer';
import { IText } from '~/types/generated/contentful';
import useContentful from '~/plugins/contentful';

export default defineComponent({
    props: {
        entry: {
            type: Object as () => IText,
            required: true,
        },
    },
    setup(props) {
        const { client } = useContentful();
        const text = useAsync(() => client.getEntry<IText>(props.entry.sys.id));

        const html = computed(() => {
            if (text.value) {
                const options: Partial<Options> = {
                    renderNode: {
                        [INLINES.ENTRY_HYPERLINK]: (node: Inline | Block) => {
                            return `<a href="/${node.data.target.fields.slug}">${node.content[0].value}</a>`;
                        },
                    },
                };
                return documentToHtmlString(text.value.fields.text, options);
            }
        });
        return {
            html,
        };
    },
});
</script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-22
    • 2020-04-21
    • 1970-01-01
    • 2023-03-13
    • 2020-02-07
    • 2019-12-09
    • 2020-02-14
    • 1970-01-01
    相关资源
    最近更新 更多