Coder Social home page Coder Social logo

requirejs-underscore-tpl's Introduction

underscore-tpl

underscore-tpl is a RequireJS plugin to load and precompile Underscore.js templates.

Here are some performance tests that show the difference when rendering precompiled templates.

Usage

Use the tpl! prefix when loading a template.

myview.js

define(['tpl!mytemplate.tpl'], function (template) {

  var MyView = Backbone.View.extend({
    template: template // just pass in the template
  });                  // do not use _.template(), at this point it is already compiled

  return MyView;
});

The plugin will compile the template after requirejs r.js optimizer.

And also when developing, it will compile the template the first time is loaded so that the next time is required it will just render the template saving a function call to underscore's internal render method.

Configuration

You can pass underscoreTemplateSettings to RequireJS config

requirejs.config({
  config: {
    underscoreTemplateSettings: {
      interpolate: /\{\{\s*([^#\{]+?)\s*\}\}/g,  // {{ title }}
      evaluate:    /\{\{#([\s\S]+?)\}\}/g,       // {{# console.log("stuff") }}
      escape:      /\{\{\{([\s\S]+?)\}\}\}/g     // {{{ title }}}
    }
  });

Dependecies

For this plugin to work you need:

License

See LICENSE

requirejs-underscore-tpl's People

Contributors

dciccale avatar fedyk avatar scotthovestadt avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

requirejs-underscore-tpl's Issues

what about model

I'm having trouble with reading model data I pass to ItemView that uses this templating plugin:

define(["app", "models/user", "tpl!html/login.html"], function (IzazovCard, User, TplLogin) {
    console.log("login");
    var user = new User();
    var LoginPage = Marionette.ItemView.extend({
        template: TplLogin,
        model: user,

        onShow: function(){
            // react to when a view has been shown
            console.log(this.model);
        }
    });

    return LoginPage;
});

Optimized templates do not import underscore dependency

I prefer not to use any global variables, and my underscore library is setup so that it can only be referenced via RequireJS dependencies. It does not exist on the global scope.

The define() call that is generated does not require underscore. This means that if you use the escape functionality within underscore, such as:

<%- variable %>

which is translated to:

_.escape(variable)

You get "_ is undefined". The code assumes, when it should not, that underscore is global.

I've fixed the issue with a very simple change and will submit a pull request.

require optimizer error when using underscore-tpl

The library has been working great but we started using the RequireJS Optimizer. The text! template references are working fine but all of the tpl! references fail with the following error. Any suggestions?

Error: Loader plugin did not call the load callback in the build:
tpl:
tpl!templates/abc.tpl
tpl!templates/xyz.tpl

onAttach and onRender are not executing

As-salamu-alikum

Zazakallah khair for sowing interest to my issue.

I am new to the marionette as well as marionette/backbone so my issue may be very stupid. Please pardon me.

My view file is

define(
		[
			"require",
			"jq",
			"jqui",
			"jqs",
			"jlb",
			"jl",
			"mt",
			"tpl!app/template/bdrLayouttpl.tpl"
		],
		function(
					require,
					jq,
					jqui,
					jqs,
					jlb,
					jl,
					mt
				){

					var Mn = require('mt');
					var tpl = require("tpl!app/template/bdrLayouttpl.tpl");
					console.log(tpl);
					var aview = Mn.View.extend
						(
							{

								template:tpl,
								regions:{
											content	: '.west',
											footer	: '.south',
											util	: '.center'
										},
								
								onAttach:function(
													options
												){console.log("in onAttach");
													jQuery(
															function($) {
																			
																			var container = $('#layout');

																			function layout() {
																				container.layout({
																									resize: false,
																									type: 'border',
																									vgap: 1,
																									hgap: 1
																					});
																			};

																			$(window).resize(layout);

																			layout();
																			layout();
																		}
														);
													},
								onRender:function(
													options
												){
													this.showChildView('content', new contentView());
													this.showChildView('footer', new footerView());
													this.showChildView('util', new utilView());
												}
							}
						);
					return new aview();
				}
	);

Component is as follows


define(function (
					require
				){
					var tk=require("tk");

					var bac = tk.Component.extend({
							ViewClass: function(options){
									if(options.border){
											return require("app/view/bapbdrView");
										}
									else if(options.doc){
											return require("app/view/bapdocView");
										}
									else
										return require("mt").View;
								}
						});
					function createBlogComponent(options){
							return new bac(options);
						};
					return createBlogComponent;
				},
		function(
					err
				){
					//The errback, error callback
					//The error has a list of modules that failed
					var failedId = err.requireModules && err.requireModules[0];
					
					console.log("In err "+failedId);
						console.log(err);
				}
	);

App is as follows

define(function (
					require
				){
						var tk=require("tk");
						var bb=require("bb");
						
						var ba = tk.App.extend({
							onStart: function(
												options
											){
												var apcomp = require("app/component/bapcomp")(options);
												apcomp.showIn(this.getRegion());
												if(bb.history){
														bb.history.start();
														if(ba.getCurrentRoute() === ""){
															this.trigger(
																//	"contacts:list"
																);
															}
													}
								},
							onBeforeStart: function(
														options
													){
														this.model = this.options.data;
								},
							onBeforeStop: function(
													options
												){
									
								},
							onStop: function(
												options
											){
									
								}
						});
						
						ba.navigate = function(route, options){
								options || (options = {});
								bb.history.navigate(route, options);
							};
						ba.getCurrentRoute = function(){
								return Backbone.history.fragment;
							};
							
						return new ba();
				},
		function(
					err
				){
					//The errback, error callback
					//The error has a list of modules that failed
					var failedId = err.requireModules && err.requireModules[0];
					
					console.log("In err "+failedId);
						console.log(err);
				}
	);

config file is as follows


requirejs.config({
    baseUrl: "assets/js/",
    paths: {
				"jquery"        		: "lib/jquery/jquery",
				"jqui"      			: "lib/jquery/jquery-ui-1.10.4",
				"jlayout"        		: "lib/jquery/jquery.jlayout",
				"jlayout.border"		: "lib/jquery/jlayout.border",
				"jquery.sizes"			: "lib/jquery/jquery.sizes",
				"backbone"      		: "lib/marionette/backbone",
				"json2"       			: "lib/json2/json2",
				"backbone.radio"		: "lib/marionette/backbone.radio",
				"backbone.marionette"   : "lib/marionette/backbone.marionette",
				"marionette.toolkit"	: "lib/marionette/marionette.toolkit",
				"underscore"        	: "lib/underscore/underscore",
				"tpl"					: "lib/require/underscore-tpl",
				"text"					: "lib/require/text"
    },
    waitSeconds: 20,
	map: {
      "*": {
				jq		:"jquery",
				bb		:"backbone",
				bbr		:"backbone.radio",
				mt		:"backbone.marionette",
				jl		:"jlayout" ,
				jlb		:"jlayout.border",
				jqs		:"jquery.sizes",
				js2		:"json2",
				tk		:"marionette.toolkit",
				us		:"underscore"
			}
		},
	config: {
				underscoreTemplateSettings: {
											  interpolate: /\{\{\s*([^#\{]+?)\s*\}\}/g,  // {{ title }} 
											  evaluate:    /\{\{#([\s\S]+?)\}\}/g,       // {{# console.log("stuff") }} 
											  escape:      /\{\{\{([\s\S]+?)\}\}\}/g     // {{{ title }}} 
    },
    shim: {
				"jqui":{
						deps: ['jq']
				},
				"jl":{
						deps: ['jq']
				},
				"jqs":{
						deps: ['jq']
				},
				"jlb":{
						deps: ['jq']
				},
				"tpl":{
						deps: ['us','text']
				},
				"us": {
					exports: "_"
				},
				"bb": {
					exports: ["Backbone"],
					deps: ['jq','us','js2']
				},
				"bbr":{
					exports: ["Radio"],
					deps: ["bb"]
				},
				"mt": {
					exports: "Marionette",
					deps: ["bb","bbr"]
				},
				"tk": {
					exports: "Toolkit",
					deps: ["mt"]
				}
    },
    deps: ['app/main']
});

But chrome js console is blank.Would you like to help me please to fix the problem?I will remain grateful to you.

Zazakallah khair again for reading by spending your valuable time with passions

Allah-hafiz

Nadvi

Override underscore template settings

Hi,

I have seen in other implementations being able to override the _.templateSettings (for different deliminters for example)

Anyway we can add this? I can open up PR based on some other libraries I have seen if you like.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.