主题开发:添加自定义句柄栏助手

Mat*_*ous 3 ghost-blog

对于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);
});
Run Code Online (Sandbox Code Playgroud)

主题级别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);
    });

    ...

};
Run Code Online (Sandbox Code Playgroud)

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

<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>
...
Run Code Online (Sandbox Code Playgroud)

在Ghost 0.4.2中有更好的方法吗?我不喜欢让用户覆盖ghost core index.js文件.

cjs*_*eon 5

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

加:

require('./helpers')();
Run Code Online (Sandbox Code Playgroud)

到顶部 config.js

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

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

module.exports = function(){  
    hbs.registerHelper('json', function(context) {
      return JSON.stringify(context);
    });
};
Run Code Online (Sandbox Code Playgroud)