4

想在 ghost cms 中实现搜索表单。访问者/用户必须能够在帖子、作者和标签中进行搜索。如果可能的话,一些 REST api 会像其他公共 ghost api 一样查询到 ghost db 并返回所需的结果。例如,下面的 api 获取所有帖子,包括标签和作者。

ghost.url.api('posts', 'slug', mySlugVariable, {include: 'tags, author'});

所以,我想要这样的东西,我可以传递一些字符串并从数据库中获取所有匹配的数据。

4

1 回答 1

2

我用js解决了。实际上,我没有找到任何好的解决方案,我在他们的 slack 小组上向幽灵团队提出了问题,他们建议我使用 js 解决这个问题。所以这就是我所做的:

API 调用

$.get(
ghost.url.api('posts', { include: 'tags, author' }))
.done(function(data) {
  localStorage.setItem('posts', JSON.stringify(data));
})
.fail(function(err) {
  console.log(err);
});

将所有数据保存到localStorage

localStorage.setItem('posts', JSON.stringify(data));

当用户在搜索表单中输入内容时,我会抓取该搜索字符串并过滤与该字符串对应的数据。

// get search results
function getSearchResult(string) {
  var postData = JSON.parse(localStorage.getItem('posts'));
  var searchResults = postData.posts.filter(function(post) {
    return post.markdown.match(string)
      || post.title.match(string)
      || post.author.name.match(string);
  });

  renderSearchResults(searchResults);
}

然后根据渲染结果

function renderSearchResults(posts) {
  // my render code
}
于 2016-04-12T07:23:36.723 回答