Templates Code Generator
Templates code generator generate JavaScript code that implements client side template mechanism from a specification tdl (Templates Description Language) file. This file contains HTML fragments with arguments place-holders.
Example
Assume that we have an array of messages (objects), each message has two fields
- img - the image of the sender.
- txt - the text content of the message.
We would like to display these messages in a readable way, in addition we would like to let the user remove messages if he wants to. The following tdl file defines a template for a message.
<templates>
<template name="msg">
<div>
<div ref="del" class="del">x</div>
<img src="${src}"/>
<div>${txt}</div>
</div>
</template>
</templates>
Using the generated code we can display messages as follow:
element.appendChild(temp.msg(img, txt));
Where element is some element (e.g. a div) where we want to append the message to, img is a url to the image and txt is the text of the message.
Note that we gave a name to the delete button, that way we can access it as follow:
var m = temp.msg(img, txt); m.del.addEventListener(...);
To see a working example create the following files:
index.html with the following content:
<!DOCTYPE html>
<html>
<head>
<title>Messages</title>
<script src="temp.js"></script>
<script src="index.js"></script>
<style>
div.del{float: right; cursor: pointer; margin: 0 5px;}
div.del:hover{color: red;}
#msgs > div{clear: both; width: 300px; margin: 5px; min-height: 30px; border: 1px solid #eeeeee;}
#msgs > div > img{float: left; margin: 0 5px;}
</style>
</head>
<body onload="load();">
<div id="msgs"></div>
</body>
</html>
index.js with the following content:
msgs = [
{img : "http://icons.iconarchive.com/icons/visualpharm/green-emo/24/kiss-icon.png", txt : "This is some message"},
{img : "http://icons.iconarchive.com/icons/visualpharm/green-emo/24/wink-icon.png", txt : "And this is another message"}
];
function load(){
function addMsg(msg){
var m = temp.msg(msg.img, msg.txt);
m.del.addEventListener("click", function(){m.style.display = "none"}, false);
document.getElementById("msgs").appendChild(m);
}
for(var i in msgs){
addMsg(msgs[i]);
}
}
temp.js this file was generated using the code generator.
Comments
You can use XML style comments.
Full Syntax
The syntax for the the tdl file is simply an XML syntax where the root tag is called templates. For every template there is a tag called template with the attribute name (its value must be unique). Inside the template tag you can write any HTML code that you want where you can replace the values of attributes and the text content of elements with variables. A variable has the form of ${id} where the id is the name of the variable (e.g ${time}).