Access and update javascript global variable inside jsrender template

I am trying to update a javascript global variable with a value from a jsrender template. How can i do this...

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

I need to have the last movie name in this javascript variable ..

+4
source share
2 answers

Custom tags and helpers can be easily registered to access or change global variables. Here is an example (code here ) that shows both paths and illustrates setting and getting global characters inside a template. Helpers / user tags are better than using {{* ...}} (since you have a better separation of code and markup), but if you use the {{* syntax, you must set allowCode=true . (See this example .)

The above approaches are ways to use your own extension to access ANY global network. However, for most scenarios, you probably only have certain specific global variables that you want to access. In this case, it is very simple to pass global parameters as parameters in the .render() call (or the .link() call if you use JsViews) as follows:

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

and then access them in any expression inside the template, for example:

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

If you want to have access to these global variables from all your templates (or for all calls to a specific template), you can instead register them as global (or specific templates) parameters for helpers / templates, you must pass them using the render / link call .

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

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

Then you access them in exactly the same way as described above using ~foo (or foo() for the function).

You will find a sample of all of these approaches on GitHub .

<h / "> UPDATE:

In addition to the documentation and examples mentioned above, http://www.jsviews.com has much more detailed documentation and examples, namely here and here .

+7
source

Not sure what you are asking. Data will not come from the template, you already have data in this object. Just use it directly:

 window.abcfx = function() { alert(movies[movies.length-1].name); } 

fiddle

0
source

Source: https://habr.com/ru/post/1433635/


All Articles