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 defined

    playground: 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.helpers is 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

    0_1608306438205_upload-3dbc8a77-11b6-4142-8c82-e64fbea5028b


  • administrators

    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 defined

    yes, this is because in the first case you tried to serialize the helperFoo and put it inside req.template.helpers, this gives you error because when you serialize the function you lost access to any variable outside the function, so the _commonDataForAllHelpers variable can not be found when helperFoo runs. 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.

    0_1608310916899_Captura de pantalla 2020-12-18 a la(s) 12.01.33 p. m..png


Log in to reply
 

Looks like your connection to jsreport forum was lost, please wait while we try to reconnect.