這篇文章教你如何創(chuàng)建你的博客貼子的一個列表,每一個條目包含標題、鏈接以及貼子內(nèi)容。
給定一個這樣的目錄結(jié)構(gòu):
/public
/posts
_data.json
my-first-post.md
my-second-post.md
/index.jade <-- or index.ejs
添加一個這樣的 /public/posts/_data.json
:
{
"my-second-post": {
"title": "My second post"
},
"my-first-post": {
"title": "My first post"
}
}
你可以在 Jade 中這樣遍歷你的貼子:
for post, slug in public.posts._data
h2: a(href="/posts/#{ slug }")= post.title
!= partial("posts/" + slug)
或者在 EJS 中:
<% for(var slug in public.posts._data){ %>
<h2><a href="/posts/<%= slug %>"><%= public.posts._data[slug].title %></a></h2>
<%- partial("posts/" + slug) %>
<% }; %>
我們正在使用 for
迭代器來遍歷 /public/posts/_data.json
中的數(shù)據(jù)。可以通過 public.posts._data
獲取到貼子數(shù)據(jù)對象。
更多建議: