我想弄清楚如何在单个页面上呈现页面集合中的所有页面。我希望我的所有帖子在生成的 index.html
中一个接一个地出现,就像在博客的首页上一样。
文件结构为
src/
index.hbs
posts/
post-1.hbs
post-2.hbs
post-3.hbs
以下内容几乎可以满足我的要求。
<section>
{{#each pages}}
<article>
<header>
<h2>{{data.title}}</h2>
</header>
{{page}}
</article>
{{/each}}
</section>
我错过了什么?
最佳答案
请原谅这个快速而肮脏的回答,我想尽快把它放在这里。我会在一两天内清理它。 (2013-09-26)
完成此工作后,我最终制作了一个 Handlebars 助手,我可以在 index.hbs
模板中使用它。有了它,我最终得到了下面的 index.hbs
的 Handlebars 模板。
index.hbs
---
title: Home
---
<p>I'm a dude. I live in Stockholm, and most of the time I work with <a href="http://www.gooengine.com/">Goo</a>.</p>
<section>
{{#md-posts 'src/posts/*.*'}}
<article>
<h2>{{title}}</h2>
{{#markdown}}
{{{body}}}
{{/markdown}}
</article>
{{/md-posts}}
</section>
文件夹结构
src/
index.hbs
posts/
post-1.hbs
post-2.hbs
post-3.md // <--- Markdown with Handlebars
Gruntfile.coffee
assemble:
options:
flatten: true
layout: 'layouts/default.hbs'
assets: 'public/assets'
helpers: 'src/helpers/helper-*.js'
root: // this is my target
src: 'src/*.hbs' // <--- Only assemble files at source root level
dest: 'public/'
src/helpers/helper-md-posts.js
这个助手采用 glob 表达式,读取文件,提取 YAML 前端内容,编译正文源,最后将其全部添加到 Handlebars block 上下文中。 帮助程序的名称有些错误,因为它实际上并不编译 Markdown...因此欢迎提出命名建议。
var glob = require('glob');
var fs = require('fs');
var yamlFront = require('yaml-front-matter');
module.exports.register = function(Handlebars, options) {
// Customize this helper
Handlebars.registerHelper('md-posts', function(str, options) {
var files = glob.sync(str);
var out = '';
var context = {};
var data = null;
var template = null;
var _i;
for(_i = 0; _i < files.length; _i++) {
data = yamlFront.loadFront(fs.readFileSync(files[_i]), 'src');
template = Handlebars.compile(data.src); // Compile the source
context = data; // Copy front matter data to Handlebars context
context.body = template(data); // render template
out += options.fn(context);
}
return out;
});
};
在这个 repo 中查看所有内容:https://github.com/marcusstenbeck/marcusstenbeck.github.io/tree/source
关于handlebars.js - 如何在一页上呈现页面集合中的所有页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18968677/