A client recently wanted to display blog tags in there search results, here's how we went about it:
1. Clone the default @hubspot/search_results module
In our case we were doing this anyway as we wanted to style the search results to match the clients blog layout.
2. Add the HTML element that will hold your tags
Wherever you want the tags to display in your search result template add <div class="blog-index__post-tags"></div>
3. Tell Hubspot you want to get the tags for your results
In the module.js:
In the function addResult add 'tags',
so the new function looks like:
function addResult(title, url, description, featuredImage, domain, tags)
In the function fillResults, we're going to add result.tags to the end of the list, so the new function looks like:
function fillResults(results) {
results.results.forEach(function(result, i) {
addResult(
result.title,
result.url,
result.description,
result.featuredImageUrl,
results.domain,
result.tags
);
});
}
4. Iterate through the tags
At the bottom of your addResult function, just after the part that adds the featured image:
if (typeof featuredImage !== 'undefined' && isFeaturedImageEnabled()) {
newResult.querySelector(
'.hs-search-results__featured-image > img'
).src = featuredImage;
}
We're going to add this code that iterates through tags if they exist:
if (tags) {
tags.forEach(function(item,i){
var node = document.createElement("a");
node.classList.add('blog-index__post-tag');
node.href = 'https://' + domain + '/tag/' + tags[i].toLowerCase().replace(/\s/g, '');
const textnode = document.createTextNode(tags[i]);
node.appendChild(textnode);
newResult.querySelector('.blog-index__post-tags').appendChild(node);
newResult.querySelector('.blog-index__post-tags').appendChild(document.createTextNode(" "));
});
}
And your all set! Replace the default search module in your search results template.
Feel free to play around with that last bit to style it how you want (see e.g. we add a space after each tag with that last appendChild, that's purely aesthetic)