Skip to content
Advertisement

HTML Templates in Javascript? Without coding in the page?

I am a web guy doing mostly Perl server-side stuff, and I’m slowly coming to a few conclusions.

  • It is far better to do most of your code via Javascript and toss data back and forth via AJAX than it is to hit submit and reload a mostly-identical page
  • I like jQuery because I like CSS, and it’s fun to chain together big long and scary-to-others definitions
  • There’s something to that templating stuff.

You want your HTML elements to look like your HTML elements, and it’s easier to define that in HTML:

<div class="sidebar_elem">
     <a href=""> TEXT</a>
</div>

Than it is to cobble up the same in Javascript or jQuery:

( '<div/>' )
     .attr('id' , 'sidebar_elem' + i )
     .addclass( 'sidebar_elem' )
     ;
( '<a/>' )
     .attr('href' , link_url )
     .appendTo( '#sidebar_elem' + i )
     ;

This is to say that I am no longer a templating agnostic, but I don’t know which templating tool to believe in. I have looked into some jQuery-based templating plugins, but I have yet to become happy with any of them, in part because the ones I’ve seen seem to want to put all that code into the page itself, which breaks the “Only markup goes into HTML files, only style goes into CSS files, only code goes into JS files” mantra I keep reciting.

So, I’m looking for a Javascript-based templating tool that would allow me to have my templates in an outside file so I can have one template change cover a series of web pages. If it’s jQuery-based, that’s great, less stuff I have to learn, but it isn’t a deal-breaker.

Advertisement

Answer

How about EJS?

Example from their page:

“EJS combines data and a template to produce HTML.”

Data:

{title: 'Cleaning Supplies',  supplies: ['mop', 'broom', 'duster'] }

Template:

<ul>
<% for(var i=0; i<supplies.length; i++) {%>
   <li><%= supplies[i] %></li>
<% } %>
</ul>

Result:

  • mop
  • broom
  • duster
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement