" , { "class" : "something" ,id:10}) しかし...">

Javascript Fluent HTML Builder

javascriptを使用してhtmlを生成するというアイデアは、私を手放しませんでした。 jQueryを使用してその本質を思い出させてください

$( "<div>" , { "class" : "something" ,id:10})







しかし、可読性が低いため、小さなライブラリが実装されました。



タグ、属性、コンテンツ



// 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 .








テンプレートエンジンの標準的なアプローチに対する利点は何ですか?



それは、より複雑で再利用可能なものにまとめることができるレンガのセットがあるという事実にあります。



問題を検討する


var items = [1,2,3]

取得したい

< ul >

< li > 1 </ li >

< li > 2 </ li >

< li > 3 </ li >

</ ul >










標準的なアプローチ。


<% if (items.length) %>

< ul >

<% for ( var item in items){ %>

< li > <% = item %> </ li >

<% } %>

</ ul >

<% } %>










標準ではない


function defaultUl(items){

if (!items.length)

return null ;

return h.ul(items.map( function (i){

return h.li(i);

}));

}



defaultUl(items);










別のリストが必要な場合は、両方のアプローチで何をしなければならないかを比較してください。



liに何かを追加する必要がありますか?

< ul >

< li id ="1" > 1 </ li >

< li id ="2" > 2 </ li >

< li id ="3" > 3 </ li >

</ ul >








質問なし。

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);

}











別の小さな例



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" );

}));



}













ソースコード



http://jshtmlbuilder.codeplex.com



プログイット



All Articles