首先,我不确定这是Wordpress问题,Gatsby问题还是GraphQL问题(或其他问题)。
我正在使用gatsby-source-wordpress构建一个Gatsby网站,以从自托管的wordpress网站提取内容。
我正在建立一个主页,用于查询最新帖子,并显示标题以及其他信息。如果标题具有特殊字符(-,&等),则它将返回标题中该字符的HTML代码(例如,“&”而不是“&”)。然后将其显示为代码,看起来很糟糕。请参阅下面的一些代码。
在没有HTML代码的情况下返回或将其转换回符号方面,我有什么选择?
这是查询的相关部分
export const homepageQuery = graphql`
query homepageQuery {
mainSection: allWordpressPost(limit: 3) {
edges {
node {
id
title
date (formatString: "MMM DD, YYYY")
featured_media {
source_url
alt_text
}
slug
categories {
id
name
link
}
}
}
}
}
这是返回单个帖子的示例
{
"data": {
"mainSection": {
"edges": [
{
"node": {
"id": "d1e9b5e0-bb8a-5e73-a89a-ba73aae92e0d",
"title": "Stories from the Bus Station Bistro & Creamery",
"date": "Jul 15, 2018",
"featured_media": {
"source_url": "https://www.storynosh.com/wp-content/uploads/2018/07/IMG_9962_3.jpg",
"alt_text": ""
},
"slug": "stories-bus-station-bistro-creamery",
"categories": [
{
"id": "3bceb083-de92-5eff-90f3-e2da524f3c2a",
"name": "Stories",
"link": "https://www.storynosh.com/category/stories/"
}
]
}
}
这是数据最终传递到的组件,用于呈现数据。
class MostRecent extends Component {
render(){
const bgimage = `url(${this.props.data.featured_media.source_url})`;
return (
<div className={`${styles.featured} ${styles['most-recent']}`} style={{backgroundImage: bgimage}} >
<div className={styles['article-info-container']} >
<h1 className={styles['featured-header']} >{this.props.data.title}</h1>
<div>
<Link to={this.props.data.categories[0].link} className={styles['category-box-link']}>
<span className={styles['category-box']}>{this.props.data.categories[0].name}</span>
</Link>
<span className={styles['featured-date']}>{this.props.data.date}</span>
</div>
</div>
</div>
)
}
}
{{3}}
答案 0 :(得分:1)
经过一堆搜索,我确实找到了这篇文章。
Unescape HTML entities in Javascript?
它成为我解决方案的基础。
我在返回组件之前在此解决方案中添加了该函数。然后创建一个变量来运行该函数并返回编码的html。
以下作品。
class SecondMostRecent extends Component {
render() {
const bgimage = `url(${this.props.data.featured_media.source_url})`
function htmlDecode(input){
var e = document.createElement('div');
e.innerHTML = input;
// handle case of empty input
return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
}
const title = htmlDecode(this.props.data.title);
return (
<div className={`${styles.featured} ${styles['second-most-recent']}`} style={{backgroundImage: bgimage}} >
<div className={styles['article-info-container']} >
<h3 className={styles['featured-header']} >{title}</h3>
<div>
<Link to={this.props.data.categories[0].link} className={styles['category-box-link']}>
<span className={styles['category-box']}>{this.props.data.categories[0].name}</span>
</Link>
<span className={styles['featured-date']}>{this.props.data.date}</span>
</div>
</div>
</div>
)
}
}
答案 1 :(得分:0)
使用dangerouslySetInnerHTML
为我解决了这个问题:
替换:<h1>{this.props.data.title}</h1>
使用:<h1 dangerouslySetInnerHTML={{ __html: this.props.data.title }} />