我在Contentful delivery API中运行查询以返回基于它的slug的特定页面项。此查询还设置了区域设置,以便它只返回我需要呈现的语言的数据。
但是,我还需要设置页面的hreflang标签,以帮助谷歌知道此页面也可以使用其他语言。
我从满足于这个代表我的页面的内容项目获得的响应似乎没有任何类型的数组属性,让我可以轻松确定内容可用的其他语言。
我认为这必须是搜索引擎优化的一个非常普遍的要求,所以希望有人能告诉我如何在Contentful的回复中得到这个?
这是我的回答的一个例子。我希望看到的是另一个名为allLocales
的属性,该属性将包含可以提供此内容的每个区域设置的列表。
更新:我知道我可以获得Space中所有语言环境的列表,以及在我的查询中设置locales=*
,但这仍然无济于事。我只需要知道我检索到的给定内容上可用的语言环境子集。例如,一个页面可能仅支持2个区域设置,但整个空间中可能有3个或更多可用区域设置。
Locales = *没有帮助,因为它包含每个链接项上的语言环境(可能有也可能没有内容),我需要的是一个单个数组对象,其中包含父内容项可用的所有语言环境。即使用户没有将内容放在字段中,我也想要明确地知道是否已在内容上选择了区域设置。
{
"sys": {
"type": "Array"
},
"total": 1,
"skip": 0,
"limit": 1,
"items": [
{
"sys": {
"space": {
"sys": {
"type": "Link",
"linkType": "Space",
"id": "xuehyxrgb9ri"
}
},
"id": "1MhAzkNYvOSU8GgUQcQKqa",
"type": "Entry",
"createdAt": "2018-01-05T10:48:30.373Z",
"updatedAt": "2018-01-05T12:57:00.066Z",
"revision": 6,
"contentType": {
"sys": {
"type": "Link",
"linkType": "ContentType",
"id": "contentPage"
}
},
"locale": "en-AU"
},
"fields": {
"title": "Test Page",
"slug": "test-page",
"content": [
{
"sys": {
"type": "Link",
"linkType": "Entry",
"id": "Vt4ktGvOE0qoO8mqeCMao"
}
},
{
"sys": {
"type": "Link",
"linkType": "Entry",
"id": "2jY5LUgHWUsaIyMuwKwYe2"
}
}
]
}
}
]
}
您可以通过查询空间来检索包含所有空间区域设置数组及其配置(例如default
和fallbackCode
)的locales对象:
要以编程方式确定给定页面可用的语言列表,您可以对/entries?content_type=contentPage&fields.slug=test-page&locale=en-AU
进行初始查询以获取页面的整个内容(包括引用的条目),然后获取顶部条目的ID并为/entries/<ENTRY_ID>?locale=*
发出另一个API请求并得到响应的fields.<LOCALIZED_FIELD>
的键。
如果相反,给定页面可用的语言列表是编辑决定,我建议添加新字段,短文本列表,使用完整的可能语言列表设置预定义值验证,并使用复选框外观。然后,作者/编辑可以选择页面可用的语言,您只需访问该语言数组的字段即可。
如果您要求当前空间,您可以实现这一目标
https://cdn.contentful.com/spaces/<you-space-id>
你会得到一个与此类似的回复:
{
"sys": {
"type": "Space",
"id": "developer_bookshelf"
},
"name": "Developer Bookshelf",
"locales": [
{
"code": "en-US",
"default": true,
"name": "U.S. English",
"fallbackCode": null
},
{
"code": "de-DE",
"default": false,
"name": "German (Germany)",
"fallbackCode": null
}
]
}
其中包含locales数组。
如果你想获得所有语言环境的条目,你只需要将locale
查询更改为locale:*
。
此外,您还可以使用js SDK实现这一目标
var contentful = require('contentful')
var client = contentful.createClient({
// This is the space ID. A space is like a project folder in Contentful terms
space: '<space-id>',
// This is the access token for this space. Normally you get both ID and the token in the Contentful web app
accessToken: '<access-token>'
})
// This API call will request an entry with the specified ID from the space defined at the top, using a space-specific access token.
const space = await client.getSpace()
console.log('space--------------------')
console.log(space)
const localizedEntries = await client.getEntries({locale: '*'})
console.log('localizedEntries--------------------')
console.log(localizedEntries)