2017年10月31日

Jekyll - 實現隨機文章功能 ( Jeykll - Generate random post links when refreshing page )

Jekyll 是一個很方便的網站、部落格產生器,它的功能夠簡潔就是專注在產生一個靜態網站。但也因為這樣,有一些需要動態產生的東西無法透過 Jekyll 直接實現。例如:每當使用者進入頁面,讓網頁產生隨機文章連結。所以,本篇將介紹如何利用 Jekyll 實現隨機文章的功能。( If you want to read this article in English, you can visit here )



產生 JSON 檔案
首先,我們來了解實現這個功能的方法。Jekyll 是沒辦法完成任何動態的功能,但是我們可以在 Jekyll 產生靜態頁面時順便建立一個 JSON 檔案,而該檔案匯集你所有文章的名稱、連結等等。最後,我們只需要在頁面中透過 JS 讀取這個 JSON 檔案並隨機挑選文章來呈現。暸解後,我們先來建立一個 JSON 檔案,例如:posts.json,然後加入以下內容:
---
---
[
{% assign posts = site.posts | where:"your-filter","filter-value" %}
{% for post in posts %}
{
    "title": "{{ post.title }}",
    "href": "{{ post.url }}"
}{% unless forloop.last %},{% endunless %}
{% endfor %}
]
以上只是一個簡單範例,看你需要什麼資料就加進去。每當你開始 build 你的網站時,完整的 posts.json 就會產生在 _site 資料夾內。


隨機選取文章資料
當我們順利產生完整的 posts.json 之後,我們就可以透過 JavaScript 來實現隨機文章的功能。在頁面中加入以下程式碼:
 ... 
<script src="//cdnjs.cloudflare.com/ajax/libs/fetch/2.0.3/fetch.js"></script>
<script>
$(function() {
  fetch('/posts.json')
    .then(function(response) {
      return response.json();
    })
    .then(function(json) {
      // Generate an random index
      var index = Math.floor(Math.random() * json.length);
      // Get the post
      var post = json[index];

      // Do things with post ...
    
    }).catch(function(error) {
      console.error(error);
    });
});
</script>
以上是一個簡單的範例,剩下的就看你需要怎麼呈現文章的相關資料。


Environment :
  ・ Unix-like System


熱門文章