我使用 contentful 来满足我们的 CMS 需求,并使用 contentful SDK for JavaScript。 我正在尝试使用他们的 documentToHtmlString 方法向我的 anchor 链接添加一些属性。 我尝试过这样做:
return documentToHtmlString(text, {
renderNode: {
[BLOCKS.PARAGRAPH]: (node, next) => {
let content: any[] = [];
node.content.forEach((item) => {
if (item.nodeType === 'hyperlink') {
let itemContent = item.content[0];
let value = itemContent['value'];
let uri = item.data.uri;
console.log(value, uri);
content.push(
`<p><a href="${uri}" data-category="contact" data-action="email">${value}</a></p>`
);
} else {
content.push(`<p>${next([item])}</p>`);
}
});
console.log(content.join(''));
return content.join('');
},
},
});
但是当我检查结果时,它没有我的数据类别或数据操作。 有没有更好的方法向链接添加属性?
他们的文档显示了这一点: https://www.contentful.com/developers/docs/javascript/tutorials/rendering-contentful-rich-text-with-javascript/
但是没有提到 anchor :(
剧情越来越复杂了…… 我想它可能不喜欢数据属性,所以我添加了一些:
content.push(
`<p><a class="test" href="${uri}" category="contact" data-category="contact" data-action="email" target="_blank">${value}</a></p>`
);
实际渲染的内容是这样的:
<a class="test" href="mailto:<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bedcd1dcfedbc6dfd3ced2db90ddd1d3" rel="noreferrer noopener nofollow">[email protected]</a>" target="_blank"><a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="93f1fcf1d3f6ebf2fee3fff6bdf0fcfe" rel="noreferrer noopener nofollow">[email protected]</a></a>
注意它是如何添加class和target,但省略category、data-category和数据操作...
感谢@stefan-judis 告诉我有关内联的信息。 我现在已将代码更新为:
[INLINES.HYPERLINK]: (node, next) => {
console.log(node);
let value = node.content[0]['value'];
let uri = node.data.uri;
return `<a class="test" href="${uri}" data="test" category="contact" data-category="contact" data-action="email" target="_blank">${value}</a>`;
},
我删除了BLOCKS代码,但不幸的是,我仍然遇到同样的问题。它不会渲染所有属性(仅类和目标)。事实上,它的渲染效果与上面完全相同。就像有一些内部格式删除了属性......
最佳答案
我创建了a quick example achieving your desired outcome .
client.getEntry("...").then(({ fields }) => {
const richText = fields.richText;
const renderOptions = {
renderNode: {
// this is the important part 👇
[INLINES.HYPERLINK]: (node, next) => {
console.log(node);
return `<a href="${
node.data.uri
}" style="background: red; color: white;" data-foo>${next(
node.content
)}</a>`;
},
[BLOCKS.EMBEDDED_ASSET]: (node, next) => {
// ...
}
}
};
document.getElementById("app").innerHTML = documentToHtmlString(
richText,
renderOptions
);
});
我不确定您的环境中发生了什么,但正如您在 CodeSandbox 上看到的,代码呈现数据属性和所有内容。 :)
关于javascript - 内容丰富的文档HtmlToString格式链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63399201/