-1

I'm currently writing my own small templating engine in javascript.

Here's how a template would look like:

<!-- Defines the template for the ribbon. -->
{{TMPL:Import=tabs.tmpl; Name=Tabs}}
<div id="{{ribbonId}}" class="ribbon">

    <!-- All the different tabs are being rendered here. -->
    {{Render:Tabs}}
</div>

You might see that in the id of the div element, I would like to render the value of ribbonId of my object.

Now, I have an object ribbon, which is defined as following:

var ribbon = { ribbonId: "mainRibbon" }

Now, how can I get on this object the value of ribbonId, by it's name?

So, the templating engine would request something like:

var templateName = ribbonId;
alert(ribbon.templateName);

In the alert, I would like to receive 'mainRibbon'.

Is something like this possible in Javascript or jQuery?

Kind regards,

Complexity
  • 5,682
  • 6
  • 41
  • 84
  • possible duplicate of [how to access object property using variable](http://stackoverflow.com/questions/11256091/how-to-access-object-property-using-variable) – ericbn May 12 '15 at 10:42

1 Answers1

1

you cannot use dot notation when variable is used as key, you need to use bracket notation, instead of :

alert(ribbon.templateName);

do

var ribbon = { ribbonId: "mainRibbon" };
var templateName = "ribbonId"; //string
alert(ribbon[templateName]);

demo:: JsFiddle

Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162