📜 ⬆️ ⬇️

Html-maker - convenient and easy generation of html using coffeescript

I want to share my small library. It is interesting to hear your opinion about it.

To the point: htmlmake is a js function that allows you to create a string with html markup inside for further insertion into a DOM tree.

Why use it?


I'll start a little from afar. I would conditionally divide modern web development into 2 categories:

If we talk about web applications, then it is logical to distribute js template engines for html generation (for example, Jade). My library is designed for 1 group, in which the most common component approach to writing js-s. When to implement a js template to generate a simple set of html elements is too expensive, usually html is generated by its jquery code. Suppose we need to collect the following html:

<div class='wrapper'><h1>, !</h1></div> 

Then usually we write something like this:
')
 $(“<div>”).addClass(“wrapper”).append($(<h1>).html(“, !”)) 

Or like this:

 $(“<div class='wrapper'><h1>, !</h1></div>”) 

And, in my opinion, such code is difficult to read and maintain. Here is an example of using my function:

 htmlString = htmlmake -> @div "wrapper", -> @h1 ", !" 

Why all the coffeescript examples?


Nested functions are written too long on native js, so I do not immediately recommend using this function to those who do not use coffeescript.

Here is a slightly more complicated example:

  html = htmlmake -> @div "hello-class", -> @ul -> @li "one" @li "two" @li "three" @a href: "http://google.com", "underworld!" 

The interface is designed as easy as possible. Immediately clear what html will be generated. Result:

  <div class='hello-class'> <ul> <li>one</li> <li>two</li> <li>three</li> </ul> <a href='http://google.com'>underworld</a> </div> 

And if I want this?


It often happens that we need to forward the context to handlers. Fortunately, in coffescript this is done with a minimum of effort. But in this case, we lose the methods that generate dom elements, so an input parameter was provided in all callbacks. Here is an example:

 @hello = "superman" html = htmlmake (hm)=> hm.span id: "super", @hello 

Result:

  <span id='super'>superman</span> 

The example is more complicated:

 @names = ["Katarina", "Diana", "Alistar"] html = htmlmake (m)=> m.div "names", (m)=> m.ul (m)=> for name in @names m.li name 

Result:

  <div class='names'> <ul> <li>Katarina</li> <li>Diana</li> <li>Alistar</li> </ul> </div> 

Thanks for attention! I will be glad to hear your criticism / advice / suggestions.

Link to the repository , well, or bower install html-maker.

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


All Articles