65.9K
CodeProject is changing. Read more.
Home

Easy JavaScript Templating

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.86/5 (4 votes)

Jan 8, 2014

CPOL
viewsIcon

8750

Below is an easy way to create Templates in JavaScript without changing the code format.

Introduction

Below is an easy way to create Templates in JavaScript files without changing your code format. edit

Background

I needed an easy way to keep my HTML clean and formated properly, when added to JavaScript files. So I came up with the following solution that seems to work well.

Using the code

All you need is the function below to keep your code clean.

// Loads formatted code from a JavaScript string variable.
function template(t) { return t.toString().replace(/^[^\/]+\/\*!?/, '').replace(/\*\/[^\/]+$/, ''); }

Easy JS Templates

To create nice looking, easy to read, easy to manage templates, follow the examples below. You won't have to worry about single or double quotes terminating your strings. Post between /*! and */ and everything should work fine.

// HTML Template Example
var html = template(function() {/*!

<html>
  <head>
    <title>JavaScript Easy Templating</title>
  </head>
  <body>
    <a id="test" href="http://www.codeproject.com">http://www.codeproject.com</a>
  </body>
</html>

*/});

// CSS Template Example
var css = template(function() {/*!

<style type="text/css">

  #test
  {
    color: red;
  }

</style>

*/});