Skip to content

Commit

Permalink
feat: add post views counter for GoatCounter
Browse files Browse the repository at this point in the history
  • Loading branch information
kungfux committed Feb 16, 2024
1 parent ed4d304 commit 44ec7d3
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 1 deletion.
4 changes: 4 additions & 0 deletions _config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,10 @@ comments:
lang: # optional, default to the value of `site.lang`
reactions_enabled: # optional, default to the value of `1`

views_counter:
active: # the option for the post views counter, e.g., 'goatcounter'.
# Keep it empty means disable. goatcounter id should be defined in 'goatcounter' section.

# Self-hosted static assets, optional › https://github.com/cotes2020/chirpy-static-assets
assets:
self_host:
Expand Down
11 changes: 11 additions & 0 deletions _includes/views-counter.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<!-- Views counter -->

{% if site.views_counter and site.views_counter.active %}
<span>
<em id="views-counter"> 0 </em>
{{ site.data.locales[lang].post.pageview_measure }}
</span>

{% capture path %}views-counters/{{ site.views_counter.active }}.html{% endcapture %}
{% include {{ path }} %}
{% endif %}
10 changes: 10 additions & 0 deletions _includes/views-counters/goatcounter.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<script>
const uri = location.pathname.replace(/\/$/, '');
const fetchPromise = fetch(`https://{{site.goatcounter.id}}.goatcounter.com/counter/${encodeURIComponent(uri)}.json`);

fetchPromise
.then((response) => response.json())
.then((data) => {
document.getElementById('views-counter').innerText = data.count;
});
</script>
4 changes: 3 additions & 1 deletion _layouts/post.html
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
- post-nav
- comments
---

{% include lang.html %}

<article class="px-1">
Expand Down Expand Up @@ -47,6 +46,9 @@ <h1 data-toc-skip>{{ page.title }}</h1>
</div>
{% endif %}

<!-- Views counter -->
{% include views-counter.html %}

<div class="d-flex justify-content-between">
<!-- author(s) -->
<span>
Expand Down

0 comments on commit 44ec7d3

Please sign in to comment.