有没有简单的方法将从Contentful API获取的Markdown文本转换为HTML代码以在HTML页面上显示。我尝试使用pagedown和一些类似的技术,但都不适用于我。
有没有简单的方法将从Contentful API获取的Markdown文本转换为HTML代码以在HTML页面上显示。我尝试使用pagedown和一些类似的技术,但都不适用于我。
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}}}
以下是我使用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>
我使用了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')
)
我在一个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;