boop
boop

Reputation: 7788

Handlebars static variables

Is it possible to register static variables for handlebars templates?

I'm using express-handlebars for my backend, where this is possible. For some specific renderings I use HandlebarsJS on the frontend where I can't find a way to accomplish this.

What I want to do is something like

handlebars.static = {foo: 'bar'}

Instead of adding it to every render

template({....., static: {foo:'bar'}});

It would be fine, if I could precompile it into each template.

Upvotes: 0

Views: 1231

Answers (1)

ekuusela
ekuusela

Reputation: 5282

Define a helper that can access your static values. Here's an example:

var templates = Handlebars.templates = Handlebars.templates || {};

/**
 * Reads property from object. Supports reading nested properties with dot or bracket notation.
 */
var readProperty = function(object, property) {
  var value = object;
  property = property.replace(/\[('|")?|('|")?\]/g, '.');
  if (property.substring(property.length - 1) === '.') {
      property = property.slice(0, property.length - 1);
  }
  property.split('.').forEach(function(name) {
    value = value[name];
  });
  return value;
};

/**
 * The object that holds the values available to all the templates. This must be accessible by the helper definition.
 */
var values = {
  key: 'a value',
  lists: {
    numbers: [0,1,2,3,5], 
  },  
};

Handlebars.registerHelper('values', function(property) {
  return readProperty(values, property);
});

templates['template-a'] = Handlebars.compile($('#template-a').html());
templates['template-b'] = Handlebars.compile($('#template-b').html());

$('body').append(templates['template-a']());
$('body').append(templates['template-b']());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://builds.handlebarsjs.com.s3.amazonaws.com/handlebars-v4.0.5.js"></script>
<script id="template-a" type="text/x-handlebars-template">
  <p>here's the value: <strong>{{values 'key'}}<strong></p>
</script>
<script id="template-b" type="text/x-handlebars-template">
  <p>again: <strong>{{values 'key'}}</strong><br>
  and another one from an array inside an object: <strong>{{values 'lists.numbers[3]'}}</strong><br>
  using bracket notation: <strong>{{values 'lists["numbers"]'}}</strong></p>
</script>

Upvotes: 1

Related Questions