Search code examples
javascriptpure-js

Is it possible to insert new HTML with pure.js


I am searching for something which renders an HTML template starting from a JSON file of data.

The matter is that the plugin/framework/library I'm searching for must create itself the <html> template structure, starting from something very simple.

For example I have an simple html like this:

<ul>
  <li><li>
</ul>

and a json like this:

{
   "mylist":{
      "listone": 
          {"img" : "/img/pippo.gif" ,
           "text1" : "pluto",
           "text2" : "topolino",
           "link" : "http://www.sito.it"        
           },
      "listtwo":
          {"img" : "/img/pippo.gif" ,
           "text1" : "pluto",
           "text2" : "topolino",
           "link" : "http://www.sito.it"        
          }
   }
}

and I want the data to render in my document like this:

<ul>
  <li>
    <img src="/img/pippo.gif" />
    <h1>pluto</h1>
    <p><a href="http:://www.sito.it>topolino</a></p>
  </li>
</ul>

If I head already the entire structure I could use pure.js as usual, but, since I don't have the inner tags in the li, can I inject the HTML code with the pure.js directives? Or is it possible only with JsRender or similar?


Solution

  • Pure JS allows you to use JavaScript function with directives. Whatever is returned from that function, will be used as a value for a directive.

    The argument of the function is an object with the following properties:

    • context : This is the full JSON that was passed for transformation
    • item* : the current loop item
    • items* : all the items of the loop
    • pos* : the current position in the loop. An integer when iterating an array, a property name iterating on a collection

    The following example shows how to do it.

    var data = {
      "img": "/img/pippo.gif",
        "text1": "pluto",
        "text2": "topolino",
        "link": "http://www.sito.it"
    }
    
    var directive = {
      'li': function (arg) {
        return "<img src=\""+arg.context.img+"\" /><h1>"
          +arg.context.text1+"</h1><p><a href=\""
          +arg.context.link+"\">"+arg.context.text2+"</a></p>"
      }
    }
    
    $('ul').render(data, directive);
    

    The given HTML:

    <ul><li></li></ul>
    

    Will become as following one (after rendering):

    <ul>
      <li>
        <img src="/img/pippo.gif">
        <h1>pluto</h1>
        <p>
          <a href="http://www.sito.it">topolino</a>
        </p>
      </li>
    </ul>
    

    I hope that will help.