简体   繁体   中英

Pass data to EJS include

I am trying to implement a recursive include in EJS. I am using ExpressJS 4. I need to be able to selectively pass in data to the include. My "sub" variable changes with loop iteration and therefore cannot work globally. However I am getting "Maximum call stack size exceeded" which means that the if statement in the partial is always evaluating to true.

This is my main HTML:

<ul id="drop1" data-dropdown-content class="f-dropdown">
<% agents.forEach (function(sub) { var subs = sub.agents; %>
<li>
    <a href="#"><%= sub.fname +' ' +sub.lname %></a>
    <% if (subs) { %>
    <% include dropdown.html %>
    <% } %>
</li>
<% }); %>
</ul>

This is my include (dropdown.html):

<ul class="f-dropdown">

    <% subs.forEach(function(sub) { %>
    <li>
    <a href="#"><%= sub.fname +' ' +sub.lname %></a>
    <% if (sub.agents && sub.agents.length) {subs = sub.agents; %>
    <% include dropdown.html %>
    <% } %>
    </li>
    <% }); %>

</ul>

UPDATE: Even this doesn't work:

<ul class="f-dropdown">
    <% if (sub.agents && sub.agents.length > 0) { %>
        <% (function(subs) { %>
            <% include dropdown.html %>
        <% })(sub.agents); %>
    <% } %>
</ul>

I'm about to try JUST

Technically, the visionmedia ejs library doesn't support passing parameters into includes. However it handles plain javascript pretty well, so you could try an IIFE closure to handle the scope changes:

<a href="#"><%= sub.fname +' ' +sub.lname %></a>
<% if (sub.agents && sub.agents.length) { %>
    <% (function() { %>
        <% var subs = sub.agents; %>
        <% include dropdown.html %>
    <% })(); %>
<% } %>

Let me know if that works for you; I'm happy to investigate further if it doesn't.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM