Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handlebars templates, access context variables with a string key

Let's say I have a handlebars template like this:

      <script id="entry-template" type="text/x-handlebars-template">
       <div class="entry">
          <h1>{{i18n.title}}</h1>
       </div>
      </script>

What I really would like to do is something like this:

var source   = $("#entry-template").html();
var template = Handlebars.compile(source);
var context = {"title.t":"My New Post"}
console.log(template(context));

When I try to parse in a context like above with a string as the key, hanslebars acts like the key is not available. I do understand that normaly the structure should be like this:

var context = {
    i18n:{
      title:'test'
    }
}

But because I'll get my 118n strings from an external source, it would be easier to just use them as keys. Ah and yes, I know projects like i18n.js, but the actual question is: Can I use a string-key in the context object with dots in it and if yes, how can I access them from the handlebars template?

like image 445
Christian Avatar asked Feb 17 '26 05:02

Christian


1 Answers

Old question, but I still want to post what I've found out.

If the key to your key:value pair is represented as a string, you could place the string itself in your handlebars template placeholder.

So if your context is:

var context = {
    "key":"value"
}

As opposed to this:

var context = {
    key: "value"
}

You could do this in your template to show the value:

<p>{{"key"}}</p>

So, handlebars will treat it as a property name, and display the value.

Example:

var names = {
    "first": "John",
    "last": "Doe"
}
<script id="names-template" type="text/x-handlebars-template">
<p>First Name: {{"first"}}</p>
</script>

Will output:

First Name: John

This respects spaces and other characters in your key strings, we tested it, and it works with dots within your strings too. Give it a try and let me know.

like image 84
RamChilla Avatar answered Feb 19 '26 20:02

RamChilla