Mustache.js is rendering html elements out of order in Can.js

153 Views Asked by At

First of all, here is some basic background information for my question.

So, in the project I am working on, we use Can.js as the rendering library, with mustache.js to facilitate live binding of elements. So for example, if I am getting some data from the server, username, I can use mustache with the following string

<h1>Hi {{username}}</h1>

which actually gets rendered into the following html

<h1>Hi Rich</h1>

This is helpful for rendering dynamic form elements, where we have a server that says, for example, this form for someUser1 should have elements a, b and c, but another person someUser2 might see only a and c.

This may look like something like the following:

<table class = 'dynamic-row-container"> 
  {{#data.elementA.isActive}}
     <tr class='elementA'>
        <td>{{data.elementA.formHeader}}</td>
        <!-- Some specific form element here... -->
     </tr>
  {{/data.elementA.isActive}}
  {{#data.elementB.isActive}}
     <tr class='elementB'>
        <td>{{data.elementB.formHeader}}</td>
        <!-- Some specific form element here... -->
     </tr>
  {{/data.elementB.isActive}}
  {{#data.elementC.isActive}}
     <tr class='elementC'>
        <td>{{data.elementC.formHeader}}</td>
        <!-- Some specific form element here... -->
     </tr>
  {{/data.elementC.isActive}}
</table>

If someUser2 accessed the form, the above html would be rendered as...

<table class = 'dynamic-row-container"> 
   <tr class='elementA'>
      <td>Element A form header</td>
      <!-- Some specific form element here... -->
   </tr>
   <tr class='elementC'>
      <td>Element C form header</td>
      <!-- Some specific form element here... -->
   </tr>
</table>

So now, this is where my problem shows up. Sometimes, when can renders the above template, my elements are appearing out of order, or sometimes, completely outside of the parent container. I have one case where a <tr>...</tr> tag is somehow being rendered completely outside of the parent <table>...</table> container! Like this below:

<tr class='elementC'>
  <td>Element C form header</td>
  <!-- Some specific form element here... -->
</tr>
<table class = 'dynamic-row-container"> 
  <tr class='elementA'>
    <td>Element A form header</td>
    <!-- Some specific form element here... -->
  </tr>
</table>

Obviously, this is invalid html, and my table ends up looking completely wrong. Has anyone ever run into this problem before, specifically when utilizing mustache with can.js? This specific problem is hard to replicate, as it seems to happen almost at random.

However, you can see the basics of the problem in this fiddle. Section A i have always showing up, then C should appear below it. However, C renders the js data in, then places the html of the element outside of the parent div container.

0

There are 0 best solutions below