javascripthtmlbootstrap-4handlebars.jshandlebarshelper

Handlebars not entering the condition even though the code seems right, doesn't give out errors


I'm having trouble figuring out what's wrong with this handlebars code, This is what it looks like:

{{#ifEquals "ciao" "ciao"}}
            <h1>########################</h1>
{{/ifEquals}}

And this is the helper:

Handlebars.registerHelper('ifEquals', function(a, b, options) {
        console.log(a)
        console.log(b)
        if (a === b) {
            return options.fn(this);
        } else {
            return options.inverse(this);
        }
      });

The problem I have is that handlebars doesn't show me the code inside the condition(<h1>########################</h1>) even if this is always true. I've checked the values with the console.log while running the site and it returns the right ones. Thanks in advance for any answer!

$(function(){   //doc ready
    let autorizzazione = getWithExpiry('autorizzazione');
    if(autorizzazione == null || autorizzazione == undefined)
    {
        window.location.replace("http://biolabitis.altervista.org/index.html");
    }
    Handlebars.registerHelper('json', function(context) {
        return JSON.stringify(context);
    });

    Handlebars.registerHelper('ifEquals', function(a, b, options) {
        console.log(a)
        console.log(b)
        if (a === b) {
            console.log(options.fn(this));
            result = options.fn(this);
            return result();
        } else {
            console.log(options.inverse(this));
            return options.inverse(this);
        }
      });

    function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)
        // if the item doesn't exist, return null
        if (!itemStr) {
            return null
        }
        const item = JSON.parse(itemStr)
        const now = new Date()
        // compare the expiry time of the item with the current time
        if (now.getTime() > item.expiry) {
            // If the item is expired, delete the item from storage
            // and return null
            localStorage.removeItem(key)
            return null
        }
        return item.value
    }

    $('#logoutBTN').click(function()
    {
        window.localStorage.removeItem("utente");
        window.localStorage.removeItem("autorizzazione");
        document.location.replace("http://biolabitis.altervista.org/index.html");
    });

    $('#buttonSubmit').click(function()
    {
        let parolachiave = $("#parolaChiave").val();
            $.ajax({
                url: `http://biolabitis.altervista.org/API/Search_All.php?q=${parolachiave}`,
                type: "GET",
                success: function(data){
                    result = data;
                    console.log(result);
                    var template= $('#template-container').html();
                    var compiledTemplate = Handlebars.compile(template);
                    $('#main').html(compiledTemplate(data)); 
                },
                error: function(){
                console.log("Errore");
                console.log(data);
                }

            });

    });

});

This is my html file (watch out i changed mainReagente to main in the javascript but still not working)

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Bio Lab ITIS</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
    <link rel="stylesheet" href="css/tabelleStyle.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script type="text/javascript" src="js/myRicerca.js"></script>
    <script type="text/javascript" src="js/handlebars.min-v4.5.3.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
  </head>

  <body>
    <div>
        <ul class="ul-modified">
          <li class="nav-item li-modified">
            <a class="nav-link" href="index.html">Pagina Principale</a>
          </li>
          <li class="nav-item li-modified">
            <a class="nav-link" href="attrezzatura.html">Attrezzatura</a>
          </li>
          <li class="nav-item li li-modified">
            <a class="nav-link" href="strumentazione.html">Strumentazione</a>
          </li>
          <li class="nav-item li li-modified">
            <a class="nav-link" href="reagenti.html">Reagenti</a>
          </li>
          <li class="nav-item li li-modified">
            <a class="nav-link" href="esperienze.html">Esperienze</a>
          </li>
          <li class="nav-item li li-modified">
            <a class="nav-link" href="pittogrammi.html">Pittogrammi</a>
          </li>
          <li class="nav-item li li-modified">
            <a id="linkRicerca" class="nav-link" href="ricerca.html">Ricerca</a>
          </li>
          <li class="li li-modified">
            <a id="logoutBTN" class="button float-right">Logout</a>
          </li>
        </ul>
      </div>


    <div class="jumbotron text-center container-sm row pt-1 divcolor mb-1">
      <div class="col-sm-2">
        <img src="immagini/logoBIOLABnoBCK.png" class="mx-auto d-block img-fluid">
      </div>
    </div>  

    <div class="input-group mb-3">
        <div class="input-group-prepend">
          <span class="input-group-text" id="basic-addon1">Parola Chiave</span>
        </div>
        <input type="text" class="form-control" placeholder="Username" aria-label="" aria-describedby="basic-addon1" id="parolaChiave">
      </div>

      <div class="mb-3">
          <button type="button" class="btn btn-lg float-right btn-color" id="buttonSubmit" data-dismiss="modal">Ricerca!</button>
      </div>
      <script id="template-container" type="text/x-handlebars-template">
        <div id="template-container">
        {{#each result}}
        {{#ifEquals "ciao" "ciao"}}
            <h1>########################</h1>
        {{/ifEquals}}
        {{#ifEquals TABELLA "reagenti"}}
          <div id="main">
            <div class="container">


              <header class="text-center mb-5 text-white">
                <div class="row">
                  <div class="col-lg-7 mx-auto">
                    <h1>Lista dei Reagenti</h1>
                  </div>
                </div>
              </header>


              <div class="card-columns">
                <!-- Produco una card per ogni record sul database-->

                <div class="card mb-5">

                  <div class="bg-white p-3 rounded-lg shadow">
                    <h1 class="h6 text-uppercase font-weight-bold mb-2">{{this.NOME}}</h1>

                    <div class="custom-separator my-4 mx-auto bg-primary"></div>

                    <ul class="list-unstyled my-5 text-small text-left">

                      <li class="mb-1">
                        <i class="fa fa-check mr-2">Formula: {{this.FORMULA}}</i>
                      </li>

                      <li class="mb-1">
                        <i class="fa fa-check mr-2">Aspetto: {{this.ASPETTO}}</i>
                      </li>

                      <li class="mb-1">
                        <i class="fa fa-check mr-2">Ditta: {{this.DITTA}}</i>
                      </li>

                      <li class="mb-1">
                        <i class="fa fa-check mr-2">Scheda di Sicurezza: {{this.SCHEDA_SICUREZZA}}</i>
                      </li>

                      <li class="mb-1">
                        <i class="fa fa-check mr-2">Quantità: {{this.QUANTITA}}</i>
                      </li>

                      <li class="mb-1">
                        <i class="fa fa-check mr-2">Scadenza: {{this.SCADENZA}}</i>
                      </li>

                      <li class="mb-1">
                        <i class="fa fa-check mr-2">Conservazione: {{this.CONSERVAZIONE}}</i>
                      </li>

                      <li class="mb-1">
                        <i class="fa fa-check mr-2">Tipo di Conservazione: {{this.TIPO_CONSERVAZIONE}}</i>
                      </li>

                      <li class="mb-1">
                        <i class="fa fa-check mr-2">Luogo di Conservazione: {{this.LUOGO_CONSERVAZIONE}}</i>
                      </li>


                      <li class="mb-1">
                        <i class="fa fa-check mr-2">Codice Internazionale: {{this.CODICE_INTERNAZIONALE}}</i>
                      </li>

                    </ul>
                  </div>

                </div>

                <!-- Fine della produzione della card per ogni reagente -->

              </div>
            </div>
          </div>
          {{else}}
          notfunctioning
          {{/ifEquals}}

          {{#ifEquals TABELLA "strumentazione"}}
          <div id="main">
                <div class="container">


                <header class="text-center mb-5 text-white">
                  <div class="row">
                    <div class="col-lg-7 mx-auto">
                      <h1>Lista della Strumentazione</h1>
                    </div>
                  </div>
                </header>

                <div class="card-deck">
                  <!-- Produco una card per ogni record sul database-->

                  <div class="card mb-5">

                    <div class="bg-white p-3 rounded-lg shadow">
                      <h1 class="h6 text-uppercase font-weight-bold mb-2">{{this.TIPO}}</h1>

                      <div class="custom-separator my-4 mx-auto bg-primary"></div>

                      <ul class="list-unstyled my-5 text-small text-left">

                        <li class="mb-1">
                          <i class="fa fa-check mr-2">Caratteristiche: {{this.CARATTERISTICHE}}</i>
                        </li>


                        <li class="mb-1">
                          <i class="fa fa-check mr-2">Tipo: {{this.ID}}</i>
                        </li>


                        <li class="mb-1">
                          <i class="fa fa-check mr-2">Numero di Inventario: {{this.N_INVENTARIO}}</i>
                        </li>

                        <li class="mb-1">
                          <i class="fa fa-check mr-2">Quantità: {{this.QUANTITA}}</i>
                        </li>


                        <li class="mb-1">
                          <i class="fa fa-check mr-2">Collocazione: {{this.COLLOCAZIONE}}</i>
                        </li>


                        <li class="mb-1">
                          <i class="fa fa-check mr-2">Collocazione del Manuale: {{this.COLLOCAZIONE_MANUALE}}</i>
                        </li>

                      </ul>
                    </div>

                  </div>

                  <!-- Fine della produzione della card per ogni Strumento -->

                </div>
              </div>
            </div>
            {{else}}
            notfunctioning
            {{/ifEquals}}

            {{#ifEquals TABELLA "attrezzatura"}}
            <div id="main">
                <div class="container">


                    <header class="text-center mb-5 text-white">
                        <div class="row">
                        <div class="col-lg-7 mx-auto">
                            <h1>Lista dell'Attrezzatura</h1>
                        </div>
                        </div>
                    </header>

                  <div class="card-deck">
                    <!-- Produco una card per ogni record sul database-->

                    <div class="card mb-5">

                      <div class="bg-white p-3 rounded-lg shadow">
                        <h1 class="h6 text-uppercase font-weight-bold mb-2 text-center">{{this.TIPO}}</h1>

                        <div class="custom-separator my-4 mx-auto bg-primary"></div>

                        <ul class="list-unstyled my-5 text-small text-left">
                          <li class="mb-1">
                            <i class="fa fa-check mr-2">Tipo: {{this.ID}}</i>
                          </li>
                          <li class="mb-1">
                            <i class="fa fa-check mr-2">Quantità: {{this.QUANTITA}}</i>
                          </li>
                          <li class="mb-1">
                            <i class="fa fa-check mr-2">Data Verifica Quantità: {{this.DATA_VERIFICA_QUANTITA}}</i>
                          </li>
                          <li class="mb-1">
                            <i class="fa fa-check mr-2">Collocazione: {{this.COLLOCAZIONE}}</i>
                          </li>

                        </ul>
                      </div>

                    </div>

                    <!-- Fine della produzione della card per ogni reagente -->
              </div>
            </div>
          </div>
          {{else}}
          notfunctioning
          {{/ifEquals}}

          {{/each}}
        </div>
      </script>


  </body>
</html>

Solution

  • It looks like you are trying to attach your template output into an element that does not exist.

    When you call $('#main').html(compiledTemplate(data));, you are asking jQuery to find the element with id="main" and to set its inner HTML to the result of calling compiledTemplate(data). But jQuery cannot find any element with id="main" because none exists in your document.

    To prove that jQuery cannot find a matching element, you could run the following: console.log($('#main').length). If the result is 0, it is because jQuery found no elements matching the selector.

    It is important to note that jQuery will not throw an Error when you call .html() (or any other method) on an empty result set. This is because even an empty result set is still a valid jQuery result Object.

    You need to add the missing element to your document: <div id="main"></div>. But note: You do not want to duplicate this ID by including it in your template. The elements with id="main" in your template need different IDs.