Comenzando con Handlebars

Handlebars.js es un motor de plantillas muy popular que es potente, fácil de utilizar y que cuenta con una gran comunidad. Se basa en el lenguaje de plantillas Mustache, pero lo mejora de distintas maneras. Con Handlebars, podrás separar el diseño HTML del resto de tu Javascript, para así escribir código mucho más limpio.

En este tutorial te vamos a enseñar todo lo que necesitas saber sobre Handlebars en pocos minutos. Puede parecer un poco abrumador al principio, pero esto es como montar en bicicleta, una vez le pillas el truco ya no se te olvida nunca más. Y además es muy sencillo, no tendrás ningún problema para adaptarlo a tus proyectos.

Adaptándolo en tus proyectos

Añadir Handlebars en tu proyecto es pan comido. Solo tienes que ir a http://handlebarsjs.com y hacer clic en el botón de download para hacerte con la última versión. En el momento de la escritura del artículo, la última versión es la 4.0.0. Ahora todo lo que tienes que hacer es incluir la librería en tu html con el típico tag script.

También puedes utilizar la versión CDN, que cuenta con la ventaja añadida de que el mismo fichero puede ser almacenado en caché en el navegador del usuario si lo ha utilizado en otro sitio web.

// From File
<script src="handlebars-v2.0.0.js"></script>

// From CDN
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0/handlebars.js"></script>

Plantillas

Una vez tengas la librería instalada, puedes empezar a desarrollar las plantillas. La manera recomendada de añadir plantillas a tu página es incluyéndolas en tags script con un tipo especial. El atributo type es importante, de lo contrario el navegador lo analizará como un archivo Javascript (que no lo es).

Las plantillas cuentan con una sintaxis fácil de entender. Pueden contener HTML y texto, mezclado con expresiones de Handlebars. Las expresiones vienen delimitadas por llaves dobles y triples {{{}}}. Estas expresiones indican a Handlebars que deben incluir el valor de las variables o ejecutar funciones de ayuda. Las plantillas necesitan ser compiladas para que se utilicen en Javascript antes de utilizarlas. Puedes ver un ejemplo a continuación. Ten en cuenta que estamos utilizando jQuery para que el trabajo con el DOM sea más sencillo, pero Handlebars puede funcionar perfectamente son él.

HTML

<!--This is our template. -->
<!--Data will be inserted in its according place, replacing the brackets.-->
<script id="address-template" type="text/x-handlebars-template">
  <p>You can find me in {{city}}. My address is {{number}} {{street}}.</p>
</script>

<!--Your new content will be displayed in here-->
<div class="content-placeholder"></div>

JS

$(function () {
  // Grab the template script
  var theTemplateScript = $("#address-template").html();

  // Compile the template
  var theTemplate = Handlebars.compile(theTemplateScript);

  // Define our data object
  var context={
    "city": "London",
    "street": "Baker Street",
    "number": "221B"
  };

  // Pass our data to the template
  var theCompiledHtml = theTemplate(context);

  // Add the compiled html to the page
  $('.content-placeholder').html(theCompiledHtml);
});

Expresiones

Para desarrollar una plantilla a partir del ejemplo anterior, cualquier dato que imprimas en una expresión {{}}, conseguirás automáticamente HTML escapado por handlebars. Esto es una gran característica en temas de seguridad, pero es posible que algunas veces quieras imprimir HTML puro. En este caso tendremos que utilizar la expresión de triples llaves {{{}}}.

Además, observa que las expresiones de Handlebars soportan valores anidados que nos permiten acceder fácilmente a los datos de un objeto de Javascript.

HTML

<script id="expressions-template" type="text/x-handlebars-template">
  {{description.escaped}}
  {{example}}

  <br><br>

  {{description.unescaped}}
  {{{example}}}
</script>

<div class="content-placeholder"></div>

JS

$(function () {
  // Grab the template script
  var theTemplateScript = $("#expressions-template").html();

  // Compile the template
  var theTemplate = Handlebars.compile(theTemplateScript);

  // Define our data object
  var context={
    "description": {
      "escaped": "Using {{}} brackets will result in escaped HTML:",
      "unescaped": "Using {{{}}} will leave the context as it is:"
    },
    "example": "<button> Hello </button>"
  };

  // Pass our data to the template
  var theCompiledHtml = theTemplate(context);

  // Add the compiled html to the page
  $('.content-placeholder').html(theCompiledHtml);
});

Contexto

Handlebars se basa en las mejores características de Mustache. Una de ellas es el concepto de contexto. Cada plantilla que implementes tiene un contexto. El nivel superior, es el objeto JavaScript que se pasa a la plantilla compilada. Pero los helpers como #each o #with lo modifican, de manera que se puede acceder a las propiedades del objeto iterado directamente. Con el siguiente ejemplo verás las cosas más claras.

HTML

<!-- The #each helper iterates over an array of items. -->
<script id="example-template" type="text/x-handlebars-template">

  <!-- people is looked up on the global context, the one we pass to the compiled template -->

  {{#each people}}

    <!-- Here the context is each individual person. So we can access its properties directly: -->
    <p>{{firstName}} {{lastName}}</p>

  {{/each}}

</script>

JS

$(function () {
  // Grab the template script
  var theTemplateScript = $("#example-template").html();

  // Compile the template
  var theTemplate = Handlebars.compile(theTemplateScript);

  // This is the default context, which is passed to the template
  var context = {
    people: [ 
      { firstName: 'Homer', lastName: 'Simpson' },
      { firstName: 'Peter', lastName: 'Griffin' },
      { firstName: 'Eric', lastName: 'Cartman' },
      { firstName: 'Kenny', lastName: 'McCormick' },
      { firstName: 'Bart', lastName: 'Simpson' }
    ]
  };

  // Pass our data to the template
  var theCompiledHtml = theTemplate(context);

  // Add the compiled html to the page
  $(document.body).append(theCompiledHtml);
});

Helpers

Handlebars no permite que escribas Javascript directamente dentro de las plantillas. Para ello, te proporciona los helpers. Esto son funciones de Javascript a las que puedes llamar desde las plantillas, y ayudar a la reutilización de código y a crear plantillas complejas. Para llamar a un helper, solo tienes que utilizarlas como una expresión, {{nombredelhelper}}. Puedes pasar parámetros así {{nombredelhelper 12345}}, en donde 12345 sería el primer parámetro de la función nombrehelper.

Para crear un helper, debes usar la función registerHelper. Echa un vistazo en el ejemplo de más abajo, en el que puedes ver cómo crear un helper...

HTML

<script id="built-in-helpers-template" type="text/x-handlebars-template">
  {{#each animals}}
    <p>
      The {{capitalize this.name}} says
      {{#if this.noise}}
        "{{this.noise}}".
      {{else}}
        nothing since its a {{this.name}}.
      {{/if}}
    </p>
  {{/each}}
</script>

<div class="content-placeholder"></div>

JS

$(function () {

  // Register a helper
  Handlebars.registerHelper('capitalize', function(str){
    // str is the argument passed to the helper when called
    str = str || '';
    return str.slice(0,1).toUpperCase() + str.slice(1);
  });

  // Grab the template script
  var theTemplateScript = $("#built-in-helpers-template").html();

  // Compile the template
  var theTemplate = Handlebars.compile(theTemplateScript);

  // We will call this template on an array of objects
  var context = {
    animals:[
      {
        name: "cow",
        noise: "moooo"
      },
      {
        name: "cat",
        noise: "meow"
      },
      {
        name: "fish",
        noise: ""
      },
      {
        name: "farmer",
        noise: "Get off my property!"
      }
    ]
  };

  // Pass our data to the template
  var theCompiledHtml = theTemplate(context);

  // Add the compiled html to the page
  $('.content-placeholder').html(theCompiledHtml);

});

Bloque de helpers

Los bloques de helpers son como los helpers normales, pero tienen una apertura y un cierre (como el #if y #each). Estos helpers pueden modificar el contenido HTML y el contenido al que envuelven. Son un poco más complicados de crear, pero son muy poderosos. Los puedes usar para reutilizar alguna funcionalidad o para crear grandes bloques de HTML de una manera reutilizable (por ejemplo, listas de elementos que se utilicen en muchos lugares de tu aplicación).

Para crear un bloque de helpers, utiliza de nuevo Handlebars.registerHelper(). La diferencia es que esta vez vamos a utilizar un segundo parámetro en nuestra función de devolución de llamada, opciones. Cuenta con una serie de propiedades útiles que vamos a necesitar. Echa un vistazo al siguiente ejemplo, en el que se convierte en mayúscula el texto.

HTML

<script id="block-expressions-template" type="text/x-handlebars-template">

  <p> The <b> {{#uppercase}} konami {{/uppercase}} </b> Code is a cheat code that appears in many video games.</p>

  <p>During the title screen before the game demo begins, the player could press the following sequence of buttons on the game controller to enable the cheat:</p>

  <p>{{#uppercase}}{{code}}{{/uppercase}}</p>

  <p>The code is also present as an Easter egg on a number of websites.</p>

</script>

<div class="content-placeholder"></div>

JS

$(function () {
  // Grab the template script
  var theTemplateScript = $("#block-expressions-template").html();

  // This is our block helper
  // The name of our helper is provided as the first parameter - in this case 'uppercase'
  Handlebars.registerHelper('uppercase', function(options) {

    // "this" is the context that existed when calling the helper.

    // The options object has a special function - fn. This is a
    // compiled version of the template that is contained between the opening and closing
    // blocks of this helper. To get a string, call fn with the context:

    return options.fn(this).toUpperCase();

  });

  // Compile the template
  var theTemplate = Handlebars.compile(theTemplateScript);

  // Define our data object
  var context = {
    "code": "up up down down left right left right b a select start"
  };

  // Pass our data to the template
  var theCompiledHtml = theTemplate(context);

  // Add the compiled html to the page
  $('.content-placeholder').html(theCompiledHtml);

});

Fuente: tutorialzine.com

COMPARTE ESTE ARTÍCULO

COMPARTIR EN FACEBOOK
COMPARTIR EN TWITTER
COMPARTIR EN LINKEDIN
COMPARTIR EN WHATSAPP