Show List of Primary Tags in Ghost
I came across this Ghost Forum post about showing a list of primary tags. There is no native Ghost helper, but here is a workaround.
Loop through posts. Then, loop through tags for each post and 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}}
All the primary tags will now be visible but with duplication. With some JavaScript, we can clean the duplicated ones.
<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>
jQuery version.
Make sure to load jQuery before that JS code.
<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>
JS code credit: https://mijokristo.com/remove-duplicate-elements-from-list-by-value-with-jquery/
Hopefully, you find this helpful.