Best practice for JS template binder - how to avoid mixing JavaScript with HTML

I would like to know if there is a good way to avoid mixing JavaScript with HTML in a BackboneJS / UnderscoreJS template app.

I understand that we need to create a code template that looks something like this:

<table cellspacing='0' cellpadding='0' border='1' > <thead> <tr> <th>Id</th> <th>Name</th> </tr> </thead> <tbody> <% _.each(items,function(item,key,list){ %> <% var f = item.name; %> <tr> <td><%= key %></td> <td class="<%= f %>"><%= item.name %></td> </tr> <% }); %> <!-- this is hardly readable --> </tbody> </table> 

What bothers me is the need to write JavaScript, inside a <%%> scriptlet, then some HTML, then some JavaScript again, a loop condition or if / else should be closed somewhere inside <%%>.

This code reminds me very much of the early days of JSP pages (JavaServer pages) - even scripts use the same notation - and I remember that this approach often caused maintenance and debugging problems. Here I had similar problems - the scriptlet is transformed by the template engine into actual JavaScript, which is not easy to analyze.

Is there a better way to handle templates? Despite the fact that I try to do so much filtering, preparing data in the backend, does it usually require some typical interface logic (for example, highlighting something, etc.)?

+4
source share

Source: https://habr.com/ru/post/1447246/


All Articles