Написание частичного имени в DOM с помощью руля / сборки

Я хочу написать HTML-комментарий до и после каждого партиала с указанием пути или названия пароли для парней, которые его реализуют.

Я могу получить путь и имя файла страницы, но не частичное. Ты знаешь как?

1 ответ

Решение

Я думаю, что я знаю, что вы имеете в виду сейчас.

Я собрал этого помощника, дайте мне знать, если это поможет.

В настоящее время помощник только добавляет комментарий перед частичным с путем к исходному частичному - который включает имя частичного. Кажется излишним также включать имя частичного, так как оно уже находится в пути, но если вы хотите, пожалуйста, добавьте запрос функции в этом репо, и я добавлю его. Мы можем легко добавить комментарий.

Вы можете установить помощника с помощью:

npm i handlebars-helper-partial

Чтобы помощник сгенерировал комментарии HTML с путем к частичному, вам необходимо определить следующее в опциях сборки (я сделал это таким образом, чтобы сделать помощника пригодным для использования и другими):

assemble: {
  options: {
    include: {
      origin: true
    }
  },
  site: {
    files: {}
  }
}

В качестве альтернативы вы можете просто добавить файл с именем include.json с:

{
  "include": {
    "origin": true
  }
}

А затем укажите путь к этому файлу в опциях сборки:

assemble: {
  options: {
    data: ['include.json', 'other/files/*.json']
  },
  site: {
    files: {}
  }
}

Вот полный код для помощника:

/**
 * Handlebars Helpers: {{include}}
 * Copyright (c) 2013 Jon Schlinkert
 * Licensed under the MIT License (MIT).
 */

var path = require('path');
var _ = require('lodash');
var yfm = require('assemble-yaml');



// Export helpers
module.exports.register = function (Handlebars, options, params) {

  'use strict';

  var assemble = params.assemble;
  var grunt = params.grunt;
  var opts = options || {};

  /**
   * {{partial}}
   * Alternative to {{> partial }}
   *
   * @param  {String} name    The name of the partial to use
   * @param  {Object} context The context to pass to the partial
   * @return {String}         Returns compiled HTML
   * @xample: {{partial 'foo' bar}}
   */
  Handlebars.registerHelper('include', function(name, context) {
    if(!Array.isArray(assemble.partials)) {
      assemble.partials = [assemble.partials];
    }

    var filepath = _.first(_.filter(assemble.partials, function(fp) {
      return path.basename(fp, path.extname(fp)) === name;
    }));

    // Process context, using YAML front-matter,
    // grunt config and Assemble options.data
    var pageObj = yfm.extract(filepath) || {};
    var metadata = pageObj.context || {};

    // `context`           = the given context (second parameter)
    // `metadata`          = YAML front matter of the partial
    // `opts.data[name]`   = JSON/YAML data file defined in Assemble options.data with a basename
    //                       matching the name of the partial, e.g {{partial 'foo'}} => foo.json
    // `this`              = YAML front matter of _either_ the "inheriting" page, or a block
    //                       expression wrapping the helper
    // `opts`              = Custom properties defined in Assemble options
    // `grunt.config.data` = Data from grunt.config.data (e.g. pkg: grunt.file.readJSON('package.json'))

    context = _.extend({}, grunt.config.data, opts, this, opts.data[name], metadata, context);
    context = grunt.config.process(context);

    var template = Handlebars.partials[name];
    var fn = Handlebars.compile(template);

    var output = fn(context).replace(/^\s+/, '');

    // Prepend output with the filepath to the original partial
    opts.data.include = opts.data.include || {};
    if(opts.data.include.origin === true) {
      output = '<!-- ' + filepath + ' -->\n' + output;
    }

    return new Handlebars.SafeString(output);
  });
};
Другие вопросы по тегам