Oct 30, 2017 Jekyll English
Jekyll 是一個很方便的靜態網站、部落格產生器,它最大的特點就是專注在產生一個靜態網站。但也因為這樣,有一些需要動態產生資料的功能就無法透過 Jekyll 直接實現。例如:每當頁面重整時,讓網頁產生隨機文章連結。但是我們還是有解決方案可以實現這個功能。所以,本篇將介紹如何利用 Jekyll 實現隨機文章的功能。
首先,讓我簡單介紹如何實現這個功能。儘管 Jekyll 無法實現動態功能,但是我們可以透過它來產生一個帶有網站文章資料的 JSON 檔案。一旦我們產生 JSON 檔案後,我們就可以使用 JavaScript 去讀取它並產生隨機文章連結。暸解後,我們就來產生這個 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 ,Jekyll 會產生一個完整的 posts.json 到 _site 資料夾下。
若你夠熟悉 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>
希望這篇文章可以讓更多人利用 Jekyll 開發更有趣的網站。
若對於文章內容有任何建議與指正,非常歡迎你告訴我或者與我一起討論 ! :)
zeckli.devforgalaxy@gmail.com © 2015-2019 zeckli, thanks to Jekyll and GitHub.