a nice easy javascript template, a embedded javascript template.
Npm: npm install nejt
Bower: bower install nejt
Description
Render the template string and the data, then set the result to be the element's innerHTML
.
Syntax
NEJT.render(templateStr, data[, element|elementId])
Parameters
- templateStr - the template string
- data - the data
- element | elementId - the container element/element's id
Returns
the result string rendered from the template string and the data.
Examples
Description
Compile the template string to a render function which can render with the data many times.
Syntax
NEJT.Compile(templateStr)
Parameters
- templateStr - the template string
Returns
the render function compile from the template string.
Examples
NEJT.render('Hello, <%= name %>.<%= age %>', {name: 'Jack'}); // 'Hello, Jack.'
var str = '<ul>\
<%for(var i=0,user,len=users.length;i<len;i++){ %>\
<li><%= users[i].name %><% if(i<len-1){ %>, <% } %></li>\
<% } %>\
</ul>';
var users = [{
name: "wwq",
age: 30
}, {
name: "hxl",
age: 32
}, {
name: "gp",
age: 33
}];
var htmlStr = NEJT.render(str, {users: users});
// delete tab and line-break
htmlStr.replace(/[\t\n]/mg, ''); //'<ul><li>wwq, </li><li>hxl, </li><li>gp</li></ul>'
NEJT.config.startTag = '[[';
NEJT.config.endTag = ']]';
var str = '[[for(var i=0,user,len=users.length;i<len;i++){ ]]\
[[= users[i].name ]]\
[[ if(i<len-1){ ]], [[ } ]]\
[[ } ]]';
var users = [{
name: "wwq",
age: 30
}, {
name: "hxl",
age: 32
}, {
name: "gp",
age: 33
}];
var htmlStr = NEJT.render(str, {users: users});
// delete tab and line-break
htmlStr.replace(/[\t\n]/mg, ''); //'wwq, hxl, gp'
NEJT.config.interpolationTag = '~';
NEJT.render('Hello, <%~ name %>.<%~ age %>', {name: 'Jack'}); // 'Hello, Jack.'
var render = NEJT.compile('Hello, <%= name %>.');
render({name: 'Jack'}); // 'Hello, Jack.'
render({name: 'Tom'}); //'Hello, Tom.'
html:
<div id="xx"></div>
<script type="text/nejt" id="users">
<ul>
<% for(var i=0,user,len=users.length;i<len;i++){ %>
<li><%= users[i].name %><% if(i<len-1){ %>, <% } %></li>
<% } %>
</ul>
</script>
javascript:
var users = [{name: "wwq", age: 30}, {name: "hxl", age: 32}, {name: "gp", age: 33}];
NEJT.render('users', {users: users}, 'xx');
<div id="a"></div>
<div id="b"></div>
javascript:
var render = NEJT.compile('Hello, <%= name %>.');
render({name: 'Jack'}, 'a');
var html = render({name: 'Tom'});
document.getElementById('b').innerHTML = html;
MIT