【发布时间】:2016-03-15 19:46:24
【问题描述】:
是否有任何简单的方法可以将 Markdown 文本从内容 api 转换为 html 代码以显示在 html 页面上。我曾尝试使用 pagedown 和一些类似的技术,但似乎没有一个对我有用。
【问题讨论】:
-
您使用什么语言编写代码?请添加,以便梅根的答案可以直接指向正确的包。
标签: reactjs markdown contentful
是否有任何简单的方法可以将 Markdown 文本从内容 api 转换为 html 代码以显示在 html 页面上。我曾尝试使用 pagedown 和一些类似的技术,但似乎没有一个对我有用。
【问题讨论】:
标签: reactjs markdown contentful
这是我使用 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>
【讨论】:
我也在 react 应用程序中做了与玛格丽塔相同的操作,但在子组件中,我从内容中提取了我的降价。
我安装了 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;
希望对你有帮助
【讨论】:
我使用过 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 并在我的子组件中使用这个模块。
【讨论】:
我知道我迟到了,但这里是使用车把的解决方案:
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}}}
【讨论】:
【讨论】: