3

对于techno 主题,我想为用户提供自定义的 hb 助手和配置。为此,我对 [ghost root]/index.js 应用了覆盖。

下面的代码在当前主题文件夹中搜索 index.js 并运行它。

var ghost = require('./core'),
    errors = require('./core/server/errorHandling');

ghost()
.then(function (param) {

    var settings = require('./core/server/api').settings;

    settings
        .read({key: 'activeTheme', context: {internal: true}})
        .then(function (result) {

            try {
                require('./content/themes/' + result.value + '/index')();
            }
            catch (e) {
                //No custom index found, or it wasn't a proper module.
            }

        });
})
.otherwise(function (err) {
    errors.logErrorAndExit(err, err.context, err.help);
});

主题级别 index.js 注入自定义博客变量(来自配置文件)和 hb 助手。

var hbs = require('express-hbs'),
    _ = require('lodash'),
    downsize = require('downsize'),
    blogVariable = require('../../../core/server/config/theme');

module.exports = function() {

    //This block allows configuration to be available in the hb templates.
    var blogConfig = blogVariable();
    var config = require('./config') || {};
    blogConfig.theme = config;
    //console.log(JSON.stringify(blogConfig));

    ////Custom hb helpers////

    hbs.registerHelper('excerpt', function (options) {

        ...

        return new hbs.handlebars.SafeString(excerpt);
    });

    ...

};

下面是使用自定义博客变量的示例。

<ul class="list-inline">
    <li><a href="{{@blog.theme.author.github}}" class="btn-social btn-outline" data-toggle="tooltip" data-placement="top" title="Github"><i class="fa fa-fw fa-github"></i></a>
    </li>
...

在 Ghost 0.4.2 中有没有更好的方法来做到这一点?我不喜欢让用户覆盖 ghost core index.js 文件。

4

2 回答 2

5

有一篇博客文章解释了如何仅通过修改config.js文件并将文件添加到根目录来执行此操作。我同意作者的观点,这更有可能是防更新的。http://zackehh.com/safely-creating-custom-handlebars-helpers/

添加:

require('./helpers')();

到顶部config.js

并将助手添加到您的helpers.js文件中,如下所示:

var hbs = require('express-hbs');

module.exports = function(){  
    hbs.registerHelper('json', function(context) {
      return JSON.stringify(context);
    });
};
于 2014-12-16T22:22:52.327 回答
0

不幸的是,不久前在论坛上有一篇关于此的帖子,但是您可以将自己的 helpers.js 文件添加到核心文件夹中......

var hbs = require('express-hbs')

// quick function for an example
registerHelper = function(){

    hbs.registerHelper('ifNthItem', function(nthItem, currentCount, offset, options) {
        if((currentCount+ offset)%(nthItem) == 0) {
            return options.fn(this);
        } else {
            return options.inverse(this);
        }
    });
};

module.exports = registerHelper;

然后只需将其链接到 index.js

var when      = require('when'),
    bootstrap = require('./bootstrap'),
    scopa = require('./helpers');

    scopa();

至少这样你不会修改核心 index.js 而是修改 helpers.js 。

于 2014-08-27T13:14:49.253 回答