BorisMoore / jsrender

A lightweight, powerful and highly extensible templating engine. In the browser or on Node.js, with or without jQuery.
http://www.jsviews.com
MIT License
2.67k stars 339 forks source link

cannot access $.templates while using jsrender without jquery #250

Closed kilnan closed 9 years ago

kilnan commented 9 years ago

I'm trying to render without jquery. It seems like I should do something like that

http://borismoore.github.io/jsrender/demos/step-by-step/20_without-jquery.html

but $.templates does not exists if I work without jquery, even if I make an empty container $ = {}.

I'm been able to do it by changing the jsrender code and storing in an external variable the function $template, but i guess I should be able to do it without changing anything.

So either I'm doing something wrong or there's something wrong.

BorisMoore commented 9 years ago

If JsRender is used without JQuery, then it does not create a global variable $. Instead it creates a global variable jsviews - so you need to use jsviews.templates, not $.templates.

But if you want to use the same code as in the samples which use jQuery, you can simply alias the jsviews variable as $.

var $ = window.jsviews;

Here are some alternative styles for doing the same thing:

var $ = window.jsviews || window.jQuery;

like here: http://stackoverflow.com/questions/27088543/jsrender-noconflict - which will work whether or not you have jQuery loaded before or after you code.

Or else, as in the example you point to, pass window.jsviews or this.jsviews into a self-executing function, to alias as $:

(function($) {
    ...
    $.templates({
        movieTemplate: document.getElementById( "movieTemplate" ).innerHTML,
        ...
   });

    document.getElementById( "movieList" ).innerHTML = $.render.movieTemplate( movies );

})(this.jsviews);
kilnan commented 9 years ago

ok, I've been very sloppy in understanding the example.

This is exactly what I needed to know, thanks!