简体   繁体   中英

How to find all the posts with a specific tag in Ghost and iterate over them?

I'm currently working on a Ghost blog (Ghost is a Wordpress "successor" that is based on Node.js and other various packages/libraries on that platform), but I'm wondering how I might be able to grab all the posts that have a certain tag in Ghost/Handlebars.js.

The problem is that Ghost's contexts are usually encapsulated to the point that I can't extract a list of all the posts bearing a certain tag out of the API; it's apparently only possible to iterate through the posts from index.hbs , and other solutions are a bit hacker-y or involve more use of jQuery.

How might I be able to get a list or array of all the posts in Ghost so that I can filter them by tag and then iterate over them? I've even tried a {{#foreach posts}} and {{#has tag='WHATEVER'}} but this method doesn't seem to work out of the box. As a newbie to Ghost and Handlebars, I'm unsure of what to do.

In case anyone comes across this still, this is now possible. Here is how you can do it via the get helper:

{{#get "posts" filter="tags:tagname"}}
    {{#foreach posts}}
         <p>{{title}}</p>
    {{/foreach}}
{{/get}}

{{#get "posts" filter="tags:[tag1, tag2]"}}
    {{#foreach posts}}
         <p>{{title}}</p>
    {{/foreach}}
{{/get}}

Note: This answer was correct at the time of writing. The {{#get}} helper was added in Nov 2015, and has been available by default since Ghost 1.0 (Aug 2017). It is documented here: https://themes.ghost.org/docs/get

David's answer should now be the accepted answer.


Listing all tags is currently not possible, as explained in the theme documentation FAQ . This also references the get helper feature on the roadmap that will make it possible in future.

One somewhat hacky possibility with the current version of Ghost is to use JavaScript to fetch the pages of RSS feed and loop through each page grabbing the tags from every post. This will work but it is worth keeping in mind that the pagination of the RSS feed will disappear in a future version (after the API becomes fully available, so there will be a migration path).

Once the get helper is released this will become a straightforward helper: {{#get 'tags'}}...do things with tags here...{{/get}} . This feature is under active development.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM