How to iterate over assets directory in jsreport?
-
Is there a mechanism in jsreport to loop over all assets and in the assets directory. I am using the handlebars engine and would like to programmatically display any images that are uploaded by a user.
-
One way is to use jsreport script, query all assets and pass it through data to the templating engines evaluation.
See an example in docs
https://jsreport.net/learn/scripts#query-an-entity-from-scriptNote this works only in jsreport v2.
-
That's fine. So, if I understand this correctly, I can create a template in the studio view, and add a script that goes along with a template? Would that be possible?
-
Yes, exactly.
-
I am struggling with how to reference the assets directory. Is there a global variable for assets in the studio?
Since I was not able to solve this, I went ahead and added a route on my server that, in theory should also work. However, I am not able to access the file names. here is my route.
Route and Template Render Functions
My handlebars template ("maps.html") is as follows:
I am not certain as to how to proceed from here. Thank you, in advance, for your time.
-
just an update, the question was solved by using the
jsreport-proxy
inside script,const jsreport = require('jsreport-proxy') async function beforeRender(req, res) { const assets = await jsreport.documentStore.collection('assets').find() req.data.assets = assets.map(a => a.name).filter(a => /.png$/.test(a)) }
with the following template:
{{#each assets}} asset name: {{./this}} <br/> <img src="{#asset {{./this}} @encoding=dataURI}" width="200px" /> <br/> {{/each}}
-
Thanks @bjrmatos