Search code examples
javascriptnode.jsejs

EJS Error: Could not find matching close tag for "<%"


I'm trying to understand what I'm skipping. It all seems correct to me but the code I'm trying to write is nested and a bit complicated so there's apparently something I don't know about EJS. posts has been passed over the EJS file from node.js. How to fix this code?

<%  for (let i = 0; i < posts.length; i++) {
          let imageSrcs = [];
          for (let j = 0; j < posts[i].images.length; j++) {
            let imageSrc = "data:image/<%= posts[i].images[j].image.contentType %>;base64,\>
                        <% posts[i].images[j].image.data.toString('base64') %>";
            imageSrcs.push(imageSrc);
          }
    %>
        initializeSlider($(".slider-<%= i+1 %>"), <%= imageSrcs %>);
    <% } %>

Solution

  • You can't use nested ejs tags. The way you have it at the moment, the first tag uses the first closing tag (the one after .contentType) to close and thus there is an extra closing tag left, since the second opening tag is being ignored.

    Changing your code to the following should fix your problem.

    <%  for (let i = 0; i < posts.length; i++) {
        let imageSrcs = [];
        
        for (let j = 0; j < posts[i].images.length; j++) {
            let imageSrc = `data:image/${posts[i].images[j].image.contentType};base64,\>
                ${posts[i].images[j].image.data.toString('base64')}`;
            imageSrcs.push(imageSrc);
        }%>
        
        initializeSlider($(".slider-<%= i+1 %>"), <%= imageSrcs %>);
        
    <% } %>