Contentful API Markdown 转换为 HTML

16

有没有简单的方法将从Contentful API获取的Markdown文本转换为HTML代码以在HTML页面上显示。我尝试使用pagedown和一些类似的技术,但都不适用于我。


2
你使用什么语言编写代码?请添加以便Meghan的回答可以直接指向正确的软件包。 - Ivan -Oats- Storck
5个回答

18

我是Contentful的客户成功经理 -

您可以在我们的常见问题解答页面上查看按语言推荐的解析器列表.

此外,如果您想联系我们,请通过单击“与我们交谈”链接在Intercom上向我们发送消息 :)


1
不知道 Contentful 是否还存在(截至2018年),聊天室像鬼城一样静悄悄的。 - Fellow Stranger

3
我知道我来晚了,但这是使用handlebars的解决方案:
var marked = require('marked');
marked.setOptions({
  renderer: new marked.Renderer(),
  sanitize: true,
  smartLists: true,
  smartypants: true
});

//Home
router.get('/', (req, res) => {
  client.getEntry('<ENTRY_ID>')
  .then( (entry)=> {
    entry.fields.body = marked(entry.fields.body);
    res.render('static/index',
     {
       entry: entry,
       user: req.user
     });
  }).catch( (err) => {
    console.log(err);
  })
});

然后在我们的index.hbs模板中,我们可以使用{{{}}}来防止转义,并调用markdown变量(entry.fields.body)。

{{{entry.fields.body}}}

这就是我们在JavaScript中只使用marked和nunjucks进行模板化的方式。你使用什么技术栈? - Will Hancock
@WillHancock 这看起来像是一个 Express + Handlebars 构建。 - MattClaff

3

以下是我使用React实现的方法:

class NewsDetail extends React.Component {
    render() {
        const body = marked(this.props.body || "");
        return (
                <div className="news-detail">
                <h2>{this.props.title}</h2>
                <div dangerouslySetInnerHTML={ { __html: body } }></div>
                </div>
        );
    }
}

Markdown内容存储在NewsDetail标签的body属性中(通过一个简短的函数将Contentful数据结构映射到我的应用程序结构中)。

HTML页面有一个脚本标签来引入marked函数:

<script src="https://cdnjs.cloudflare.com/ajax/libs/marked/0.3.6/marked.min.js"></script>

值得一提的是,在直接设置元素HTML之前,您应该对Markdown进行清理。您可以使用DOMPurify来获取经过消毒的输出,这将防止XSS攻击。 - David B

2

我使用了ReactMarkdown模块,如果您也有一个React应用程序: https://github.com/rexxars/react-markdown

示例: npm install --save react-markdown

const React = require('react')
const ReactDOM = require('react-dom')
const ReactMarkdown = require('react-markdown')

const input = '# This is a header\n\nAnd this is a paragraph'

ReactDOM.render(
  <ReactMarkdown source={input} />,
  document.getElementById('container')
)

我正在通过props传递Markdown,并在我的子组件中使用此模块。

0

我在一个React应用程序的子组件中也像Margarita一样做了同样的事情,并从Contentful中提取了我的Markdown。

我安装了react-markdown包

使用

npm install react-markdown

import React from "react";
import ReactMarkdown from "react-markdown";

const AboutIntro = (props) => {
    return (
        <div>

            <h2 className="about__intro-title">
                {props.aboutTitle}
            </h2>

            <ReactMarkdown>
                {props.aboutCopy}
            </ReactMarkdown>

        </div>
    )
}
export default AboutIntro;

希望这可以帮到你。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接