Search code examples
javascriptjsrender

Accessing a global javascript variable inside jsrender template and updating it


I am trying to update a global javascript variable with a value from jsrender template. How can I accomplish it...

i have created a fiddle http://jsfiddle.net/4RH7n/8/

i need to have the last movie name into that javascript variable..


Solution

  • Custom tags and helpers can easily be registered to access or modify global variables. There is a sample here (code is here) which shows both ways, and illustrates both setting and getting globals from within a template. Helpers/custom tags are better than using {{* ...}} (since that way you have better separation of code and markup) - but if you do use {{* syntax you have to set allowCode=true. (See this example).

    The above approaches are ways of using your own extension to be able to access ANY global. However, for most scenarios, you probably only have certain specific globals you want to access. In that case it is really easy to pass the global(s) in as options on the .render() call (or the .link() call if you are using JsViews) like this:

    ...render(myData, { foo: myFooGlobal, bar: myBarGlobal });
    

    and then access them in any expression within the template, such as like this:

    ... {{:~foo}} ... {{for ~bar}} ... {{/for}} ...
    

    If you want to be able to access those globals from all your templates, (or for all calls to a specific template) you can instead register them as global (or template specific) helpers/template parameters, and then you don't need to pass them in with the render/link call.

    For example, to register them globally, for all templates:

    $.views.helpers({
        foo: myFooGlobal,
        bar: myBarGlobal 
    });
    

    You then access them in exactly the same way as above, using ~foo (or foo() for a function).

    You'll find sample of all of these approaches on GitHub.


    UPDATE:

    In addition to the documentation and samples referenced above, there are much more recent documentation and samples on http://www.jsviews.com, and specifically here and here.