first iteration of related articles

This commit is contained in:
Gabriele Musco 2021-04-15 07:46:53 +02:00
parent 6bd3eda2cb
commit cfc7d25449
No known key found for this signature in database
GPG Key ID: 8539FD3454380B83
4 changed files with 51 additions and 0 deletions

View File

@ -84,6 +84,10 @@ summaryLength = 70 # number of words for article summaries
infiniteScrolling = false # activates infinite scrolling instead of regular pagination infiniteScrolling = false # activates infinite scrolling instead of regular pagination
enableFooterColumns = false # activates footer columns, as described below enableFooterColumns = false # activates footer columns, as described below
# related articles will be selected randomly based on tags and shown at
# the bottom of the article, after the comments
enableRelatedArticles = false
relatedArticlesNum = 2 # how many related articles to show
[menu] [menu]
# these links will be added to the main navigation menu, sorted by weight # these links will be added to the main navigation menu, sorted by weight

View File

@ -434,3 +434,9 @@ ul.list {
} }
} }
} }
.relatedArticlesContainer {
#relatedArticles .postlistitem {
@extend .featuredCard;
}
}

View File

@ -30,4 +30,5 @@
></script> ></script>
<div id="commento"></div> <div id="commento"></div>
{{ end }} {{ end }}
{{- partial "related_articles.html" . -}}
{{ end }} {{ end }}

View File

@ -0,0 +1,40 @@
{{ 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 }}