Helpers - use top level variables and functions
-
I want to be able to use some common variables and functions within a template helper script file, but I get :
ReferenceError: [var/function] is not definedplayground: https://playground.jsreport.net/w/anon/u7zM~nRJ
Is there a way to do this?
var _commonDataForAllHelpers = "hello"; function helperFoo() { // this fails with: ReferenceError: _commonDataForAllHelpers is not defined console.log(_commonDataForAllHelpers); return "bar"; } function beforeRender(req, res, done) { req.template.helpers += '\n' + helperFoo done(); }
-
Since
req.template.helpersis a string that seems to be evaluated as a complete script, seems like we just need to somehow get the entire "helper" script included (this is how global helpers do it: https://github.com/jsreport/jsreport-assets/blob/0c379acb498d24e55aa1a154b89344b02b11917c/lib/assets.js#L377)Something like this maybe?
function beforeRender(req, res, done) { req.template.helpers += '\n' + `\n{#asset ./helpers_src_asset.js}` done(); }with the asset as:
var _commonDataForAllHelpers = "hello"; function helperFoo() { console.log(_commonDataForAllHelpers); return _commonDataForAllHelpers; }I've updated the playground: https://playground.jsreport.net/w/anon/u7zM~nRJ

-
hi!
I want to be able to use some common variables and functions within a template helper script file, but I get :
ReferenceError: [var/function] is not definedyes, this is because in the first case you tried to serialize the
helperFooand put it insidereq.template.helpers, this gives you error because when you serialize the function you lost access to any variable outside the function, so the_commonDataForAllHelpersvariable can not be found whenhelperFooruns. this is basically how javascript works with functions getting serialized and the revived, the function is no longer a closure and lost access to other variables outside its definition.Something like this maybe?
your second case works ok, you just have a small typo here
'\n' +\n{#asset ./helpers_src_asset.js}it should be'\n' +\n{#asset ./helpers_asset.js}, you can use that approach or just enable the shared helpers check of the asset which basically does the same.