List of Primary Tags

Hi all,

I basically want to get a list of primary tags and a list of regular tasks. I can return a list of all tags but I am unsure on how to filter it to just return the primary tags (and do the same to just return the regular ones).

This is how I return all the tags, but how can I filter to just return the primary tags? Thanks!

    {{#get "tags" as |tag|}}
    <div class="dropdown">
        <ul class="dropdown-menu">
            {{#foreach tag}}
            <li><a class="dropdown-item tag" href="{{url}}">{{name}}</a></li>
            {{/foreach}}
        </ul>
    </div>
    {{/get}}

Primary tags only exist in the context of a post (the same tag could be primary_tag in one post and a normal one in another).
The tag object doesn’t have a property to identify it as primary:

1 Like

This is a workaround.

  1. Loop through posts
  2. Loop through tags for each post. Limit the tags to one, which will be the primary tag.
{{#get 'posts' include='tags'}}
  {{#foreach posts}}
    {{#foreach tags limit='1'}}
    <li class='item' data-slug='{{slug}}'>
      <a href='{{ url }}'>{{ name }}</a>
    </li>
    {{/foreach}}
  {{/foreach}}
{{/get}}
  1. All the primary tags will be now visible but with duplication. With some JS, you can clean the duplicated ones.
<script>
$(document).ready(function() {
  var found = {};
  $('.item').each(function() {
    var $this = $(this);
    if(found[$this.attr('data-slug')]) {
      $this.remove();
    } else {
      found[$this.attr('data-slug')] = true;
    }
  });
});
</script>

Make sure jQuery is loaded before that JS code. JS code credit: https://mijokristo.com/remove-duplicate-elements-from-list-by-value-with-jquery/

Update (None jQuery Code):

<script>
  var finalList = { },
      elements = document.querySelectorAll('.item');

  elements.forEach( element => {
    if (finalList[element.dataset.slug]) {
      element.style.display= 'none';
    } else {
      finalList[element.dataset.slug] = true;
    }
  });
</script>
1 Like

Amazing, it worked. Thank you so much! I really like your Ghost Tips & Tricks series, great work. Please share any blogs, tutorials or videos that you may have I would like to learn more :blush:

1 Like

Pleasure, Jesus! I regularly publish new content on Aspire Themes blog and the tips page. Also, @Tiago shares some great content at https://www.thestackjunction.com/

2 Likes

Thanks for the mention @ahmadajmi :grinning:

I also share some stuff about Ghost on YT if you’re into it: https://www.youtube.com/channel/UCRwkVyZXSWS1VIgnWd3j_LA

2 Likes