" , { "class" : "something" ,id:10}) ...">
📜 ⬆️ ⬇️

Javascript fluent html builder

The idea of generating html using javascript didn't let me go. I will remind her essence with jQuery
$( "<div>" , { "class" : "something" ,id:10})

but since readability leaves much to be desired, a small library has been implemented.

Tags, attributes, and content


// var h = Htmls .
h.div() == '<div></div>'
// .
h.div().Class( "some" ).Id(10) == '<div class="some" id="10"></div>'
// $(), .
h.div().$( "some text" ) == '<div>some text</div>'


* This source code was highlighted with Source Code Highlighter .


What is the advantage over the standard approach of template engines?


I see it in the fact that we have a set of bricks that we can assemble into something more complex and reusable.

Consider the task

var items = [1,2,3]
want to get
< ul >
< li > 1 </ li >
< li > 2 </ li >
< li > 3 </ li >
</ ul >


')
Standard approach.

<% if (items.length) %>
< ul >
<% for ( var item in items){ %>
< li > <% = item %> </ li >
<% } %>
</ ul >
<% } %>



Not standard

function defaultUl(items){
if (!items.length)
return null ;
return h.ul(items.map( function (i){
return h.li(i);
}));
}

defaultUl(items);



Compare what we have to do with both approaches if we need another list.

Need to add something to li?
< ul >
< li id ="1" > 1 </ li >
< li id ="2" > 2 </ li >
< li id ="3" > 3 </ li >
</ ul >


No problem.
function defaultUl(items, trans){
if (!items.length)
return null ;
return h.ul(
items.map( function (i){
return trans(h.li(i),i);
}));
}
defaultUl(items, function (tag, item){
return tag.Id(item);
}



Another small example


var persons =
[{id:1,name: "First" , balance: 100},
{id:2,name: "Second" , balance: -200},
{id:3,name: "Third" , balance: 300}];



< table >
< tr >< th > Name </ th >< th > Balance </ th ></ tr >
< tr id ="1" class ="green" >< td > First </ td >< td > 100 </ td ></ tr >
< tr id ="2" class ="red" >< td > Second </ td >< td > -200 </ td ></ tr >
< tr id ="3" class ="green" >< td > Third </ td >< td > 300 </ td ></ tr >
</ table >



var tr = function (tag, items){
return h.tr(items.map( function (x){ return tag(x);}));
};

h.Head = function (){
var args = Array.prototype.slice.call(arguments);
return tr(h.th, args);
};

h.Row = function (){
var args = Array.prototype.slice.call(arguments);
return tr(h.td, args);
};

with (Htmls) {

var htmlPart = table(
Head( "Name" , "Balance" ),
persons.map( function (p){
return Row(p.name, p.balance).Id(p.id).Class(p.balance > 0 ? "green" : "red" );
}));

}




Sources


http://jshtmlbuilder.codeplex.com

Progg it

Source: https://habr.com/ru/post/102943/


All Articles