Búsqueda de artículos en Blog de Hubspot

html+hubl

<div class="hs-search-results">
    <template class="hs-search-results__template">
      <div class="">
            <a class=" echo_url_img" href="">
              <img class="echo_image" src="">
            </a>
            <span>
                <span class="echo_date"></span>
                <span class="echo_tag"></span>               
            </span>
            <h2><a href="" class="echo_url echo_title"></a></h2>
            <p class="echo_description"></p>
            <a class="echo_url_btn" href="">Leer más</a>
       </div>
    </template>
  
    <div class="hs-search-results__pagination" data-search-path="{{ site_settings.content_search_results_page_path }}">
        <a href="" class="hs-search-results__prev-page"></a>
        <a href="" class="hs-search-results__next-page"></a>
    </div>

    <main class="page-content">
        <section class="">
            <div class="content-buscar">
                <form action="/busqueda">
                    <input type="hidden" name="type" value="BLOG_POST">
                    <input class="buscar" placeholder="Buscar..." type="text" name="term">
                    <button class="buscar-btn" type="submit"></button>
                </form>
            </div>
            <div id="ajax-content">
                <div id="hsresults" class="hs-search-results__listing"></div>
            </div>
        </section>
    </main>
</div>  

JS para la búsqueda

String.prototype.truncate = function(){
    var re = this.match(/^.{0,25}[\S]*/);
    var l = re[0].length;
    var re = re[0].replace(/\s$/,'');
    if(l < this.length)
        re = re + "&hellip;";
    return re;
}
var hsResultsPage = function(_resultsClass) {
  function buildResultsPage(_instance) {
    var resultTemplate = _instance.querySelector(
        '.hs-search-results__template'
      ),
      resultsSection = _instance.querySelector('.hs-search-results__listing');
      /*searchPath = _instance
        .querySelector('.hs-search-results__pagination')
        .getAttribute('data-search-path'),
      prevLink = _instance.querySelector('.hs-search-results__prev-page'),
      nextLink = _instance.querySelector('.hs-search-results__next-page'),
      pag1Link = _instance.querySelector('.pag_1'),
        pag2Link = _instance.querySelector('.pag_2'),
        pagdotsLink = _instance.querySelector('.pag_dots'),
        paglastLink = _instance.querySelector('.pag_last');*/

    var searchParams = new URLSearchParams(window.location.search.slice(1));

    function getTerm() {
      //colocar título de busqueda
      document.querySelector('.buscar').value = searchParams.get('term') || '';
      return searchParams.get('term') || '';
    }
    function getOffset() {
      return parseInt(searchParams.get('offset')) || 0;
    }
    function getLimit() {
      return parseInt(searchParams.get('limit')) || 9;
    }
    function addResult(title, url, description, featuredImageUrl, authorFullName, tags, unixdate) {
      var newResult = document.importNode(resultTemplate.content, true);
      function isFeaturedImageEnabled() {
        if (
          newResult.querySelector('.mBlog-imagen')
        ) {
          return true;
        }
      }
      function prettyDate(date) {
        var months = ['enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio',
                'julio', 'agosto', 'setiembre', 'octubre', 'noviembre', 'diciembre'];
        return date.getUTCDate()+' de '+months[date.getUTCMonth()] + ' ' + date.getUTCFullYear();
      }
      
      var date_format = prettyDate(new Date(unixdate));
      
      newResult.querySelector('.echo_date').innerHTML = date_format;
      if(tags.length > 0){
        newResult.querySelector('.echo_tag').innerHTML = "| "+tags[0];
      }
      //newResult.querySelector('.echo_authorFullName').innerHTML = authorFullName;
      var title = title.replace(" - La Casa AmarillaLa Casa Amarilla", "");
      newResult.querySelector('.echo_title').innerHTML = title;
      newResult.querySelector('.echo_url_img').href = url;
      newResult.querySelector('.echo_url').href = url;
      newResult.querySelector('.echo_url_btn').href = url;
      newResult.querySelector(
        '.echo_description'
      ).innerHTML = description.truncate();
      if (typeof featuredImageUrl !== 'undefined' && isFeaturedImageEnabled()) {
        /*newResult.querySelector(
          '.thumbnail'
        ).src = featuredImage;*/        
        newResult.querySelector(
          '.echo_image'
        ).src = featuredImageUrl;
      }
      resultsSection.appendChild(newResult);
    }
    function fillResults(results) {
      results.results.forEach(function(result, i) {
        //console.log(result);
        addResult(
          result.title,
          result.url,
          result.description,
          result.featuredImageUrl,
          result.authorFullName,
          result.tags,
          result.publishedDate
        );
      });
    }
    function emptyPagination() {
      prevLink.innerHTML = '';
      nextLink.innerHTML = '';
    }
    function emptyResults(searchedTerm) {
      resultsSection.innerHTML =
        '<div class="hs-search__no-results"><p>Disculpa. No se encontraron resultados para "' +
        searchedTerm +
        '"</p>' +
        '</div>';
    }
    function setSearchBarDefault(searchedTerm) {
      var searchBars = document.querySelectorAll('.hs-search-field__input');
      Array.prototype.forEach.call(searchBars, function(el) {
        el.value = searchedTerm;
      });
    }
    function httpRequest(term, offset, limit) {
      var SEARCH_URL = '/_hcms/search?',
        requestUrl = SEARCH_URL + searchParams + '&analytics=true&limit='+limit,
        request = new XMLHttpRequest();

      request.open('GET', requestUrl, true);
      request.onload = function() {
        if (request.status >= 200 && request.status < 400) {
          var data = JSON.parse(request.responseText);
          setSearchBarDefault(data.searchTerm);
          if (data.total > 0) {
            fillResults(data);
            paginate(data);
          } else {
            emptyResults(data.searchTerm);
            emptyPagination();
          }
        } else {
          console.error('Error, al retornar resultados.');
        }
      };
      request.onerror = function() {
        console.error('Sin respuesta del servidor.');
      };
      request.send();
    }
    function paginate(results) {
      var updatedLimit = getLimit() || results.limit;
      function hasPreviousPage() {
        return results.page > 0;
      }
      function hasNextPage() {
        return results.offset <= Math.ceil(results.total/9) - 1;
      }

      if (hasPreviousPage()) {
        var prevParams = new URLSearchParams(searchParams.toString());
        /*prevParams.set(
          'offset',
          results.page * updatedLimit - parseInt(updatedLimit)
        );*/
        //prevLink.href = '/' + searchPath + '?' + prevParams+'&offset='+(results.offset-1);
        prevLink.setAttribute("onclick","location.href = '"+'/' + searchPath + '?' + nextParams+'&offset='+(results.offset-1)+"';");
        prevLink.innerHTML = '<';
      } else {
        prevLink.parentNode.removeChild(prevLink);
      }

      if (hasNextPage()) {
        var nextParams = new URLSearchParams(searchParams.toString());
        /*nextParams.set(
          'offset',
          results.page * updatedLimit + parseInt(updatedLimit)
        );*/
        nextLink.setAttribute("onclick","location.href = '"+'/' + searchPath + '?' + nextParams+'&offset='+(results.offset+1)+"';");
        nextLink.innerHTML = '>';
        
        /*active links*/
        last_pag = Math.ceil(results.total/9);
        if(last_pag > 0){
          pag1Link.classList.remove('active');
          if(results.offset == 0){
             pag1Link.classList.add('active');
             }
          pag1Link.setAttribute("onclick","location.href = '"+'/' + searchPath + '?' + nextParams+'&offset=0'+"';");
        }
        if(last_pag > 1){
          pag2Link.classList.remove('active');
          if(results.offset == 1){
             pag2Link.classList.add('active');
             }
          pag2Link.setAttribute("onclick","location.href = '"+'/' + searchPath + '?' + nextParams+'&offset=1'+"';");
        }
        if(last_pag > 2){
          paglastLink.classList.remove('active');
          if(results.offset == last_pag-1){
             paglastLink.classList.add('active');
             }
          paglastLink.innerHTML= last_pag;
          paglastLink.setAttribute("onclick","location.href = '"+'/' + searchPath + '?' + nextParams+'&offset='+(last_pag - 1)+"';");
        }
        /*end active links*/
        
      } else {
        nextLink.parentNode.removeChild(nextLink);
      }
    }
    var getResults = (function() {
      if (getTerm()) {        
        httpRequest(getTerm(), getOffset(),  getLimit() );
      } else {
        emptyPagination();
      }
    })();
  }
  (function() {
    var searchResults = document.querySelectorAll(_resultsClass);
    Array.prototype.forEach.call(searchResults, function(el) {
      buildResultsPage(el);
    });
  })();
};

if (
  document.attachEvent
    ? document.readyState === 'completo'
    : document.readyState !== 'cargando'
) {
  //mostrar resultados en
  var resultsPages = hsResultsPage('div.hs-search-results');
} else {
  document.addEventListener('DOMContentLoaded', function() {
    //mostrar resultados en
    var resultsPages = hsResultsPage('div.hs-search-results');
  });
}
 
Share on facebook
Share on twitter
Share on linkedin