Click here to Skip to main content
11,412,111 members (63,270 online)
Click here to Skip to main content

Easy JavaScript Templating

, 8 Jan 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
Below is an easy way to create Templates in JavaScript without changing the code format.


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


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() {/*!

    <title>JavaScript Easy Templating</title>
    <a id="test" href=""></a>


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

<style type="text/css">

    color: red;




This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Software Developer (Senior) Codevendor
United States United States
Please visit my personal website for my latest codes and updates.


Comments and Discussions

-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150414.5 | Last Updated 8 Jan 2014
Article Copyright 2014 by M@dHatter
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid