Search code examples
javascripthtmldust.js

How to pass a variable into a dust helper function key?


I'm creating a dust helper function which will access a global JS object that holds my text. I need to be able to also pass in a variable from the model that the dust helper function will use. My dust helper looks something like...

var global = {
    lesson_titles: [
        "Lesson 1",
        "Lesson 2",
        "Lesson 3"
    ],
    lesson1: {
        a: "This is lesson1.a"
    }
};

dust.helpers.global = function ( chunk, context, bodies, params ) { 
    var key = params.key;
    var parts = key.split(".");
    var current = global;
    for(var i = 0; i < parts.length; i++) {
        current = current[parts[i]];
    }
    chunk.write(current);
};

And the intended use is in my dust file is something like...

{@global key="lesson1.a"}

This works fine, but for one of my models that I pass in, I have a variable called "lesson_index". I'd like to be able to use that variable in the key to be able to access things correctly. For example...

{@global key="lesson_titles.{lesson_index}"}

lesson_index will be 0, 1, or 2 and would then correctly grab the correct lesson title depending on its index. What's the correct index for this?


Solution

  • Just a note-- you're reinventing the wheel a little bit by writing a global helper. Dust includes a global object as part of a Dust context that is automatically accessed during reference lookups. If you have a specific need to access a global that you can't pass into the context, that's OK, but it means you'll do extra work.

    To resolve any references within a string, you can use the special context function context.resolve. You only need to change one line of your code:

    var key = context.resolve(params.key);
    

    This function will use your current context to render the string in params.key, so key will evaluate to lesson_titles.1.