How to access handlebars engine from jsreport-handlebars?
-
Trying to add a new template to handlebars but the reference used by jsreport is via jsreport-handlebars.
const handlebars = require('jsreport-handlebars')
and when I try to use handlebars.registerHelper("... it tells me registerHelper is not a function.
I did try to go directly like this const handlbars=require('handlebars') . but when I run the report it of course says template not available because I am going around jsreport's instance.
Any way I can get a handle to the handlebar engine used by jsreport's so I can add custom templates?
can see here how I have all the jsreport-* in node modules
![alt text]( image url)and can see how I am accessing it inside my report.js file:
and can see when I try to add a template.. it fails to find the registerHelper function
certainly appreciate any insight how to access. I saw where we can add functions as well.. but never saw 'where' we add functions.. I mean what js file..
-
hi!
Trying to add a new template to handlebars but the reference used by jsreport is via jsreport-handlebars.
const handlebars = require('jsreport-handlebars')
and when I try to use handlebars.registerHelper("... it tells me registerHelper is not a function.
I did try to go directly like this const handlbars=require('handlebars') . but when I run the report it of course says template not available because I am going around jsreport's instance.
Any way I can get a handle to the handlebar engine used by jsreport's so I can add custom templates?why you want to use handlebars directly? i mean, it is not mean to be accessed directly because it is an implementation detail of jsreport. jsreport has its way to register handlebars helpers (just pass the helpers content functions as string in the
.helpers
property of the template that you are going to render), so there is no need to register the helpers using handlebars api, you can do it with jsreport. you can see here how the shape of the object that you pass to.render
will look like when using template's helpers
-
Hi. Thank you for responding. I ended up doing that but then every client has to pass in the helpers.. I would rather do it on the server to create common helpers. Each client can of course add their own but I have some very common ones I created that are used across multiple reports. I tried to declare a function in my reports.js but somehow they were not found. Any idea what the magic is to enable a function declared in my reports.js to pass them as helpers?
-
I would rather do it on the server to create common helpers. Each client can of course add their own but I have some very common ones I created that are used across multiple reports. I tried to declare a function in my reports.js but somehow they were not found
you can do that too using assets too, you can create an asset and mark it as "shared helpers", with that, the content of the asset (functions defined inside) will be attached to all templates in your installation and you will be able to use those common/shared helpers inside each of your template. you can see an example of this here in our playground
-
That is a GREAT idea.. how would I mark it as a 'shared helper' ? and where?
-
The playground is great but not good for how to set that up in code.. because the playground is doing a lot of things behind the scenes. What I am missing here is how to, in my reports.js pasted above, how to enable even 'assets'. I am importing assets as you can see: const assets = require('jsreport-assets'). According to the assets documentation I can do something like {#asset MyHelpersAssets.js}. Is that right?
-
IS there a way I can use handlebar helpers and add my own? any example of that?
https://github.com/helpers/handlebars-helpers
-
how would I mark it as a 'shared helper' ? and where?
look at the example i linked, here is the option specifically:
in jsreport-core you will need to create the asset using document store api and when inserting the asset you can pass
isSharedHelper: true
to the object that is going to be inserted.jsreport.documentStore.collection('assets').insert({ name: 'shared-helpers.js', content: '<put here your functions>', isSharedHelper: true })
The playground is great but not good for how to set that up in code.. because the playground is doing a lot of things behind the scenes. What I am missing here is how to, in my reports.js pasted above, how to enable even 'assets'. I am importing assets as you can see: const assets = require('jsreport-assets'). According to the assets documentation I can do something like {#asset MyHelpersAssets.js}. Is that right?
our intention is not to teach how to use
jsreport-core
yet, because it is a low level library with docs that are not ready (yet) for someone to guide by himself, that is why we offer jsreport package that comes ready to use and with studio UI that simplifies a lot of things and can do everything thatjsreport-core
can do.jsreport-core
docs are not ready and lot of things are not mentioned there so if you for some reason prefer to usejsreport-core
instead ofjsreport
you will quickly find questions when trying to do more advanced things and right now it is not our priority to answer questions about low level details of jsreport (even that, you can see that i'm trying to help you as much as possible with some of these low level details), it takes too much time to answer those kind of questions aboutjsreport-core
when there is a package ready to use like jsreportIS there a way I can use handlebar helpers and add my own? any example of that?
check the docs, there is a section where that is described, just install the package, ensure that you have this config enabled, then require it and use it inside the helpers section of the template.
you should try jsreport package directly if your intention is to develop reports quickly, but if you have the time to try to use
jsreport-core
directly then you should be ready to discover some things and details by yourself checking the code, tests available in our github repositories
-
![alt text]( image url)
I have been trying to do the import as defined in the link you shared:
const handlebars = require('handlebars');const helpers = require('handlebars-helpers')({
handlebars: handlebars
});but the issue is the example we used is using jsreport-handlebars .. as I said way at the top of this thread. It seems to be 'hiding' the handlebar and the handlebar-helpers won't add to it.. I get at type error. on handle bars.. since it is not the right one . I posted an issue here:https://github.com/jsreport/jsreport-handlebars/issues/5
So I am trying :) .. just somehow the jsreport is doing something to handlebar that is breaking accessing the underlying 'handlebar' .. very confusing as you can see.
and am using js report core.. and I paid $$ for a license that includes enterprise support.
-
btw.. the
jsreport.documentStore.collection('assets').insert({
name: 'shared-helpers.js',
content: '<put here your functions>',
isSharedHelper: true
})was very helpful.. thanks for sharing that.
-
some things i think you are just getting confused by assuming something wrong:
i'm not sure why you expect to get handlebars when using
require('jsreport-handlebars')
, what is exported fromrequire('jsreport-handlebars')
is a module that is designed to work as a jsreport extension, not the handlebars dependency. also doing this is wrong:const helpers = require('jsreport-handlebars'); jsreport.use(helpers({ handlebars: handlebars });
, as i say, what is exported fromrequire('jsreport-handlebars')
is not handlebars package so don't treat it like that, you will be only confused by doing that.the docs says this:
There are plenty of thirdparty libraries providing additional handlebars helpers like handlebars-helpers or handlebars-intl. To use such a library in jsreport, you need to install it from npm and then require it at the top of the template's helpers.
i will highlight the following: require it at the top of the template's helpers, so this code:
const handlebars = require('handlebars'); const helpers = require('handlebars-helpers')({ handlebars: handlebars });
should be in the helpers section of the template that you are rendering, not in the code that you use to initialize jsreport.
jsreport.render({ template: { content: '...some template content here...', helpers: ` const handlebars = require('handlebars'); const helpers = require('handlebars-helpers')({ handlebars: handlebars }) `, engine: 'handlebars', recipe: 'chrome-pdf' } })
something that i don't understand, i see that you have
jsreport
installed but you are manually usingjsreport-core
and manually applying extensions. why? you will be doing the same by just using jsreport package directly, so i'm not sure i understand why you need to usejsreport-core
if you installedjsreport
too in the same project. it is not clear to me what you are trying to do by just seeing parts of your code, maybe you have a valid use case to usejsreport-core
directly but i can't see it.
-
yah could be. I was given this code to take over and trying to learn as I go :). let me read your response and see if I can un-confuse myself ! Thanks!
-
btw.. still broke... getting type error.. I think because when I pass in the handlebars-require in the helper section of the template it still has to load it.. and it is breaking on that same error.
perhaps you can help me figure how to to not us ether jsreport-core.. as you suggested I may not need it. I do have js report loaded in the project.
here is my entire class.. how would I use just jsreport rather than js-report core?
I am running this under node on AWS.. if that helps ?
import config from 'config'; import AWS from 'aws-sdk'; import uuid from 'uuid/v4'; import { Logger } from './common'; const log = new Logger(); const path = require('path'); const os = require('os'); const jsreport = require('jsreport-core')({ connectionString: { name: 'fs', syncModifications: true } } ) const jsrender = require('jsreport-jsrender') const handlebars = require('handlebars') const templates = require('jsreport-templates') const xlsx = require('jsreport-xlsx') const data = require('jsreport-data') const scripts = require('jsreport-scripts') const assets = require('jsreport-assets') const helpers = require('handlebars-helpers'); const phantomPdf = require('jsreport-phantom-pdf') const fsStore = require('jsreport-fs-store') let initialized = false let ready = false let readyCallbacks = []; jsreport.use(jsrender()) jsreport.use(handlebars()) jsreport.use(helpers({ handlebars: handlebars })) jsreport.use(templates()) jsreport.use(xlsx()) jsreport.use(data()) jsreport.use(scripts()) jsreport.use(assets()) jsreport.use(phantomPdf()) jsreport.use(fsStore({ dataDirectory: path.join( os.tmpdir(), 'jsreport' ) })) export class Reporting { constructor() { } initialize() { log.debug("Initialize Reporting"); return new Promise( (resolve, reject) => { if (! initialized ) { initialized = true; log.debug("invoking jsreport.init()"); jsreport.init().then( () => { ready = true; for(let i=0;i<readyCallbacks.length;++i) readyCallbacks[i](); return resolve(); }).catch( err => { log.error("JSReport Init error", err); return reject(err); }) } else if (! ready ) { readyCallbacks.push( () => { resolve() }); } else { log.debug("jsreport already initialied."); return resolve(); } }); } report(body) { const self = this; return new Promise( (resolve, reject) => { self.initialize().then( () => { jsreport.render(body).then( (response) => { return resolve(response); }).catch( (err) => { log.error("JSReport render error", err); return reject(err); }); }).catch( err => { log.error("JSReport self init error", err); return reject(err); }); }); } }
-
since it was not mentioned in any of the previous comments, i was assuming that you were using latest version of jsreport-core which is
2.1.0
, but after seeing your last comment it is clear that you are using jsreport-corev1
. please in the future try to be more specific about the versions that you are using, it saves us a lot of time in trying to figure it out what can be the problems or confusion that you are getting.here is a minimal example that shows how
handlebars-helpers
works normally injsreport-core
.package.json
{ "name": "jsreport-core-handlebars-helpers", "version": "0.0.1", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "BJR Matos <bjrmatos@gmail.com> (https://github.com/bjrmatos)", "license": "MIT", "dependencies": { "handlebars-helpers": "0.10.0", "jsreport-core": "1.5.1", "jsreport-handlebars": "1.1.2", "jsreport-phantom-pdf": "1.4.6" } }
index.js
const path = require('path') const fs = require('fs') const jsreport = require('jsreport-core')({ tasks: { allowedModules: '*' } }) jsreport.use(require('jsreport-handlebars')()) jsreport.use(require('jsreport-phantom-pdf')()) jsreport.init().then(() => { console.log('jsreport started') jsreport.render({ template: { // here i'm passing inline content of the template, but you can also pass "shortid" of template, if you have one stored content: ` number using "abs" helper from handlebars-helpers: {{abs -100}} `, helpers: ` const handlebars = require('handlebars'); const helpers = require('handlebars-helpers')({ handlebars: handlebars }); `, engine: 'handlebars', recipe: 'phantom-pdf' } }).then((response) => { const outputPath = path.join(__dirname, 'result.pdf') fs.writeFile(outputPath, response.content, (err) => { if (err) { return console.error('Error while saving report output:', err.message) } console.log('report saved in:', outputPath) }) }).catch((err) => { console.error('jsreport render error:') console.error(err) }) }, (e) => { console.error('Error while starting jsreport:') console.error(e) })
screenshoot that shows that it works:
please analyze the example that i'm giving to you and adapt it to your case. as you can see it works normally, so if you are having problems it is likely you are just getting confused.
perhaps you can help me figure how to to not us ether jsreport-core.. as you suggested I may not need it. I do have js report loaded in the project.
the example will be the same using just
jsreport
instead ofjsreport-core
, it even has less code:package.json
{ "name": "jsreport-handlebars-helpers", "version": "0.0.1", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "BJR Matos <bjrmatos@gmail.com> (https://github.com/bjrmatos)", "license": "MIT", "dependencies": { "handlebars-helpers": "0.10.0", "jsreport": "1.10.0" } }
index.js
const path = require('path') const fs = require('fs') const jsreport = require('jsreport')({ // you can define these options in file "jsreport.config.json" too tasks: { allowedModules: '*' } }) jsreport.init().then(() => { jsreport.render({ template: { // here i'm passing inline content of the template, but you can also pass "shortid" of template, if you have one stored content: ` number using "abs" helper from handlebars-helpers: {{abs -100}} `, helpers: ` const handlebars = require('handlebars'); const helpers = require('handlebars-helpers')({ handlebars: handlebars }); `, engine: 'handlebars', recipe: 'phantom-pdf' } }).then((response) => { const outputPath = path.join(__dirname, 'result.pdf') fs.writeFile(outputPath, response.content, (err) => { if (err) { return console.error('Error while saving report output:', err.message) } console.log('report saved in:', outputPath) }) }).catch((err) => { console.error('jsreport render error:') console.error(err) }) }, (e) => { console.error('Error while starting jsreport:') console.error(e) })
again, analyze the example here and i'm sure you can remove
jsreport-core
and just usejsreport
in your own code.
-
OK.. nice!.. let me give it a shot. And I thought I was on the last.. my bad.. thanks for the help over the weekend!
-
@bjrmatos I managed to get this running and your help was instrumental.. really appreciate your help and patience.
I did upgrade to the new version .. and spent the day trying to move from phantom to chrome and still working on that..but his original issue has been resolved. Thank you
-
Hi @bjrmatos. Something has happened, somehow, and the code no longer works. I created a small project with the code above.. and as you can see the helper is no longer there.
Here are the screen shots. Please help as our entire reporting service is down. I assume something must have changed in the way jsreport is loading these?
Please offer some suggestions
-
The same code works for me. I would suggest to delete node_modules and package-lock.json and do new install using
npm i
.
-
Hi Jan.. good morning, or evening wherever you are :) , well I just created that project a few minutes before posting.. copied the code and ran it . all fresh. Let me do the npm i and try.
-
I got this error... I have no idea .. I am googling to see. unless you have any idea?
I am on a Mac btw..2018-09-07T13:32:43.140Z - debug: Base url not specified, skipping its injection.
2018-09-07T13:32:43.141Z - debug: Rendering engine handlebars
2018-09-07T13:32:43.300Z - warn: Error when processing render request Error while executing templating engine. require of "handlebars" module has been blocked. To be able to require custom modules you need to add to configuration { "allowLocalFilesAccess": true } or enable just specific module using { templatingEngines: { allowedModules": ["handlebars"] }.1 |
2 | const handlebars = require('handlebars');
| ^
3 |
4 | const helpers = require('handlebars-helpers')({
5 | handlebars: handlebarsError: require of "handlebars" module has been blocked. To be able to require custom modules you need to add to configuration { "allowLocalFilesAccess":true } or enable just specific module using { templatingEngines: { allowedModules": ["handlebars"] }
at _require (/Users/raphaelchancey/RayTestCode/node_modules/jsreport-core/lib/render/safeSandbox.js:63:19)
at Object.apply (/Users/raphaelchancey/RayTestCode/node_modules/vm2/lib/contextify.js:288:34)
at evaluate-template-engine-helpers.js:2:28
at Script.runInContext (vm.js:74:29)
at VM.run (/Users/raphaelchancey/RayTestCode/node_modules/vm2/lib/main.js:212:72)
at run (/Users/raphaelchancey/RayTestCode/node_modules/jsreport-core/lib/render/safeSandbox.js:171:19)
at module.exports (/Users/raphaelchancey/RayTestCode/node_modules/jsreport-core/lib/render/engineScript.js:114:7)
at process.<anonymous> (/Users/raphaelchancey/RayTestCode/node_modules/script-manager/lib/worker-processes.js:48:36)
at process.emit (events.js:180:13)
at emit (internal/child_process.js:783:12)
jsreport render error:
-
This is error from jsreport v2. And I saw on previous screen you are using jsreport 1.10.0.
So you should not see this if you have done fresh install based on the package.json on the screen.