Website-Redesign/layouts/partials/related_articles.html

41 lines
1.6 KiB
HTML
Raw Normal View History

2021-04-15 00:46:53 -05:00
{{ if and (.Site.Params.enableRelatedArticles | default false) .Params.tags }}
<div class="relatedArticlesContainer">
<hr />
<h2>More posts like this</h2>
<div id="relatedArticles"></div>
</div>
{{- partial "js_paginator.html" . -}}
<script>
function hasAnyTags(articleTags, targetTags) {
for (let atag of articleTags) {
if (targetTags.includes(atag)) return true;
}
return false;
}
function getRelatedArticles() {
let currentTags = {{ .Params.tags }};
let targetContainer = document.getElementById('relatedArticles');
targetContainer.innerHTML = '';
fetch('/search/index.json').then(res => res.json())
.then(res => {
let candidates = res.pages.filter(
a => hasAnyTags(a.tags, currentTags) && a.link != "{{ .Permalink }}"
);
let targetNum = Math.min(
{{ .Site.Params.relatedArticlesNum | default 2 }},
candidates.length
);
if (candidates.length <= 0) {
Array.from(
document.getElementsByClassName('relatedArticlesContainer')
).map(e => e.style.display = 'none');
}
for (let i=0; i<targetNum; i++) {
targetContainer.innerHTML += renderSingleArticle(candidates[i]);
}
});
}
getRelatedArticles();
</script>
{{ end }}