Getting a tag with a certain description in the context of a post

I’m trying to get a tag with a particular description in the context of the post . I’m trying to do something like this but not sure if the syntax is right or even possible
{{#if tags description='vehicle-make'}}
<option>{{name}}</option>
{{/if}}

there will be multiple tags with the description ‘vehicle-make’ but only one per post, this way I can get the name from that tag. I can’t just set this as the primary tag because I need to do the same thing with the ‘vehicle-model’ and ‘vehicle-year’ tags

essentially what I want to do is like below but instead of filtering through all the tags, I want to filter all the tags in the context of the current post
{{#get 'tags' filter='description: vehicle-year'}}
{{#foreach tags }}
<option>{{name}}</option>
{{/foreach}}
{{/get}}

I think this would be approached with JavaScript backing up the Handlebars templating.

Below is an example of how I would tackle it. I’ve created a select element that contains all the tags in my site that have a description of “vehicle-make”. I’ve also listed all the tags from the currently viewed post in a data attribute on the select element, just exposing the slug and splitting them with a vertical pipe.

The JavaScript takes the select element and loops through each select option to find if it’s in the posts tags, by comparing the options to the value of the data attribute:

{{#post}}

<select id="select" data-posttags="|{{#if tags}}{{#foreach tags}}{{slug}}|{{/foreach}}{{/if}}">
  {{#get 'tags' filter='description:vehicle-make'}}
    {{#foreach tags}}
      <option value="{{slug}}">{{name}}</option>
    {{/foreach}}
  {{/get}}
</select>

<script type="text/javascript">
  // Grab select element
  const select = document.querySelector('#select');

  // Run through the select options
  [...select.options].map(option => {
    // If any option matches part of the tags in 'data-posttags' set it to selected = true
    if (select.dataset.posttags.includes(option.value)) {
      option.selected = true;
    }
  });
</script>

{{/post}}

There’s a few benefits to this: Firstly that if the JavaScript breaks everything will still work as expected and elements won’t disappear. Secondly it’s performant, we’re not asking the server to give us everything when most of it is already on the page.

I hope this all makes sense! Any questions just ask :blush:

Thanks @DavidDarnes, this looks like it should work for me.

1 Like