有没有什么简单的方法可以将 Markdown 文本从内容丰富的 api 转换为呈现在 html 页面上的 html 代码。我曾尝试使用 pagedown 和一些类似的技术,但似乎没有一个对我有用。
内容丰富的 api 降价转换为 HTML
IT技术
reactjs
markdown
contentful
2021-05-08 03:17:24
4个回答
我知道我迟到了,但这是使用把手的解决方案:
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}}}
我使用过 ReactMarkdown module:如果你还有一个 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传递降价并在我的子组件中使用这个module。
这是我使用 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 属性中(通过一个将内容数据结构映射到我的应用程序结构的简短函数)。
HTML 页面有这个脚本标签来拉入marked
函数:
<script src="https://cdnjs.cloudflare.com/ajax/libs/marked/0.3.6/marked.min.js"></script>
其它你可能感兴趣的问题