Search code examples
javascriptarraysjsonhandlebars.js

Manipulate an array using javascript and displaying it via Handlebars


I'd like to work on a data array containing only strings, which can be manipulated using js/jq easily (like adding/modifying string values) and displayed via handlebars. This array can be of any format either js array or JSON data (whichever works with handlebars best) What type of array should i use, and how should i achieve it? Thanks

My data will be in this form:

"flightno": "F10001",
"origin": "Sydney",
"destination": "Delhi"

so for example: the flightno changes depending on what the user selects through the html form, then this flightno is displayed on the html page through handlebars expression.


Solution

  • You can use simple JSON. On change of origin or destination set the json data and compile a handlebar template. Then append the html to the element.

    Say your json looks like this

    var data = {
      "flightno": "F10001",
      "origin": "Sydney",
      "destination": "Delhi"
    };
    

    Say your DOM looks like this

    <div>
      <select name="origin" id="origin">
        <option>1</option>
        <option>2</option>
      </select>
      <select name="destination" id="destination">
        <option>1</option>
        <option>2</option>
      </select>
      <div class="flightno"></div>
    </div>
    

    Your handlebars template for flightno will be

    template = Handlebars.compile('<div class="someclass">{{flightno}}</div>');
    $('#flightno').html(template(data));