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

use jsrender on requirejs not load correct #287

Closed Rhain closed 8 years ago

Rhain commented 8 years ago

I use jsrender on requirejs . use shim config deps in requirejs.config() like blow:

                 shim: {
            'jsrender':{
                deps:['jquery'],
                exports:'jsrender'
            }

        }

when I used jsrender to render template on requirejs,most of times I get this error Uncaught TypeError: $(...).render is not a function , some times it works ok.

It seems like jsrender not load in a correct order. How can I fix this?

I use requirejs like below:

requirejs( ['js/config'] , function(config){
        require([
            'jquery','jsrender'
            ], function($, jsrender){

                $("#id").render({a:'a'});
        });
    });
BorisMoore commented 8 years ago

jsrender.js is already an AMD-enabled script, (and it does not require jQuery - so it will not in itself force loading of jQuery as a dependency). So I believe your shim will not work - as implied by this:

http://requirejs.org/docs/api.html#config-shim:

requirejs.config({
    //Remember: only use shim config for non-AMD scripts,
    //scripts that do not already call define(). The shim
    //config will not work correctly if used on AMD scripts,
    //in particular, the exports and init config will not
    //be triggered, and the deps config will be confusing
    //for those cases.

For examples of loading JsRender with requirejs, see: https://github.com/BorisMoore/jsrender/blob/master/test/unit-tests-amd-scriptloader.html. and https://github.com/BorisMoore/jsrender/blob/master/test/unit-tests/tests-jsrender-amd-scriptloader.js

If you want to force loading of jQuery before JsRender, you can always use this approach:

https://github.com/BorisMoore/jsrender/blob/master/test/unit-tests/tests-jsrender-amd-scriptloader.js#L63-L73

You have also the option of using JsRender without requiring jQuery as in:

requirejs( ['js/config'] , function(config){
    require(['jsrender'], function(jsrender){
        var tmpl = jsrender.templates(document.getElementById("id"));
        tmpl.render({a:'a'});
    });
});
Rhain commented 8 years ago

@BorisMoore Thanks very much ,you really help me out!

BorisMoore commented 8 years ago

Good. Closing this now.