Using ejs with child-templates: how to pass 'this?'

  • I have noticed that with handlebars you can do the following:

    // In parent report (engine = handlebars, recipe = phantom-pdf)
    {{#each children}}
      {#child child-report}
    // In child report (engine = none, recipe = html)
    <h2>{{Name}} (age {{Age}})</h2>

    But there does not seem to be an 'each' equivalent for EJS. I've tried this, as per the EJS help page on the jsreport site:

    // parent (engine = ejs, recipe = phantom-pdf)
    <h1><%= title %></h1>
    <% for(var i = 0; i < children.length; ++i) { %>
      {#child child-report}
    <% } %>
    // child (engine = none, recipe = html)
    <h2><%= Name %> (age <%= Age %>)</h2>

    But age and name are obviously undefined, because I am not using the child in children[i].

    To pass in children[i], I've tried this, which fails to parse:

    {#child child-report @data=children[i]}

    I've also tried this, which did not work because it defined self, but self.Name was undefined in the child template.

    {#child child-report @data.self=children[i]}

    As a last attempt, I tried this, which did not work (this is defined, but not this.Name or Name on its own):

    {#child child-report @data.this=children[i]}

    Is there a special @data trick that I am missing, or does the child template functionality require additional code to work with EJS?

    We have a lot of existing templates in EJS so it would be great to keep using them with jsreport.

    Thanks in advance!

  • Update: this works, but it is fragile (someone could change the parent template and break the child template without realizing it):

    // parent template
    <% for(var i = 0; i < children.length; ++i) { %>
        {#child child-report}
    <% } %>
    // child template
    <h2><%= children[i].Name %></h2>

    This option also works in a similarly fragile, but slightly better, way:

    // parent
    <% for(var i = 0; i < children.length; ++i) { %>
        <% const me = children[i] %>
        {#child child-report}
    <% } %>
    // child
    <h2><%= me.Name %></h2>

    It would still be nice to be able to somehow reassign this so that the child template will scope as expected.

  • administrators

    i think that the big problem is that @data does not support passing objects, with that you can re-assign the scope of the child template from the parent template.

    we have an issue open for that feature, so we will take a look at this very soon.

Log in to reply

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