Click here to Skip to main content
13,194,662 members (87,804 online)
Click here to Skip to main content
Add your own
alternative version

Stats

4.6K views
6 bookmarked
Posted 7 Jan 2014

Easy JavaScript Templating

, 7 Jan 2014
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.

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>

*/});

License

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

Share

About the Author

M@dHatter
Software Developer (Senior) Codevendor
United States United States
Please visit my personal website http://www.codevendor.com for my latest codes and updates.

Raise Bid

You may also be interested in...

Pro
Pro

Comments and Discussions

 
PraiseThanks ! Pin
manuel23118-Feb-16 3:43
membermanuel23118-Feb-16 3:43 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.171018.2 | Last Updated 8 Jan 2014
Article Copyright 2014 by M@dHatter
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid