Question

given I have this javascript file

src/js/functions.js

(function() { 

    crc32 = function(str, crc ) { 
    ...
    }; 
})();

This file is part of the static website, and I want to use crc32() in a template, like this:

index.hbs

<script type="text/javascript" charset="utf-8">
    var crc_checksum = {{checksum solution}};
</script>

Of course that needs an intermediate helper

helpers.js

Handlebars.registerHelper('checksum', function(value){
    this.checksum = return value;
});    

I don't want to copy-paste the crc32 code into the helper (as this would duplicate the code). Is there any way of loading an external JS-file into the namespace of the helper?

Était-ce utile?

La solution

You could build your crc32 file in the "node.js" way and use browserify to use it in your site. There are also other ways to make your crc32 object available on both node and the browser. Then you can require it in your helper file...

src/js/functions.js

(function(exports) {
  exports.crc32 = function (str, crc) { ... };
})(window || module.exports);

helpers.js

var crc32 = require('./src/js/functions').crc32;
Handlebars.registerHelper('checksum', function (value) {
  return crc32(value);
});

Autres conseils

Sure, when creating a helper just follow the same module pattern you would with any other node library.

Wrap the helper in a module.exports.register function:

module.exports.register = function (Handlebars, options, params) {
  Handlebars.registerHelper('checksum', function(src) {
    return require('your-checksum-lib')(src);
  });
};

And then make sure to tell Assemble where the file is:

assemble: {
  options: {
    helpers: ['path/to/checksum.js']
  }
}

Or... if the helper is actually a npm module itself, you can add it to the devDependencies and keywords in package.json and Assemble will automatically pick it up. e.g:

{
  "name": "foo",
  "devDependencies": {
    "handlebars-helper-checksum": "~0.1.0",
  },
  "keywords": [
    "handlebars-helper-checksum"
  ]
}

However, you could also just make a request or pr for this helper on the handlebars-helpers repo, and we could add it to the library.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top