The following code loads templates.
tpl = {
// Hash of preloaded templates for the app
templates: {},
// Recursively pre-load all the templates for the app.
// This implementation should be changed in a production environment. All the template files should be
// concatenated in a single file.
loadTemplates: function(names, callback) {
var that = this;
var loadTemplate = function(index) {
var name = names[index];
console.log('Loading template: ' + name);
$.get('tpl/' + name + '.html', function(data) {
that.templates[name] = data;
index++;
if (index < names.length) {
loadTemplate(index);
} else {
callback();
}
});
}
loadTemplate(0);
},
// Get template by name from hash of preloaded templates
get: function(name) {
return this.templates[name];
}
};
and u can load templates like
tpl.loadTemplates(['header', 'wine-details', 'wine-list-item'], function() {
});
But here the templates are defined in seperate html file.
Is it possible all my templates are defined in one html file and i load them all together.
Do i need to write some kind of parser. The reason is for my home page i have 40 templates and I dont want to create 40 Html template pages instead it would be i can keep them in one single html page and than load them all together.
Is this possible?
Yes you don't need to be doing it like this.
Check this: https://github.com/requirejs/text
define([
'some/module',
'text!some/module.html',
'text!some/module.css'
], function (SomeModule, HtmlFile, CssFile) {
'use strict';
// ....
}
This can load text resources. When you are ready to deploy your app you can compile all your js files and templates into a single minified file using r.js. You can do this via command line, or as a grunt or gulp task.
There are many template libraries which you can find requirejs plugins for (often extended off that text plugin ^^). For example this one for Handlebars https://github.com/jfparadis/requirejs-handlebars or this one for underscore https://github.com/jfparadis/requirejs-tpl. Just google search "requirejs «template engine name»".
If you want to have multiple templates in one html file you need a way to separate them. The nicest way to do this is using the new template tag.
You can, define templates single file, under different container with Ids. load single html the way you are loading here, create a jquery node with template html, run through children read id attribute and save html of each child saved as that.templates[id_you_read] = child.html();
But this is not the right way of doing stuff. use requirejs with text plugin as in the prev answer.
Related
I'd like to load a handlebars partial, but only when the URL is '/foo', and load a different partial for '/bar'.
I know that this is always going to be a bit of a hack, and not really intended - but use to the project handlebars structure, it seems the most logical way of solving the problem I'm running into.
Thanks
assuming
jquery is included
your template files are in the same folder
your template files have the names "foo.bs" & "bar.hbs"
code
function loadTemplate(templateName) {
$.get(templateName + '.hbs', function (data) {
var template = Handlebars.compile(data);
$(body).html(template(jsonData));
}, 'html');
}
if (window.location.pathname.search('bar') !== -1) {
loadTemplate('bar');
}
if (window.location.pathname.search('foo !== -1) {
loadTemplate('foo');
}
I have one function in a JS file which should ideally be used by multiple html pages. I don't want to duplicate this function to another file. Currently, my js file starts like this:
(function(){
var app = angular.module('Project1', []);
and the first html that has been using this JS is obviously called Project1.
I want 'Prject2' html to use this JS to, and I tried this:
(function(){
var app = angular.module('Project1', 'Project2' []);
However, this doesn't work. Any idea of how I can utilize this AngularJS file for multiple html pages without duplicating the desired functions?
simply add your js reference (and angular refrences) into both of your html pages
do note that add them after adding angularjs references
You can create your first module as you did in your first sample.
Your next sample can then use the 'Project1' by setting up a dependency to that module, like so:
var app = angular.module('Project2', ['Project1']);
Is there a standard workaround for something like this in ASP.NET:
//myinclude.js
$(document).ready(function() {
for(recs=0; recs < {{server-side-value}}; recs++) {
// process records
}
});
Note this is a js file. I know about WinForms ability to insert dynamic quoted scripts into the page. But how about a page's js file that is dependent on server-side values? I know you can use something like:
//myview.cshtml
var instance = new MyObject(<%= ServerSideValue =%>);
and include it on the page to pass it to the js file, but I'm wondering about the architecture of keeping js separate from html code so that an html/css designer can work with the template free of javascript; keeping everything separate. I primarily use MVC now.
What are some of the patterns to deal with this? Is the only solution dynamically inserting js into the actual page or having partial views included separately into the page.? Or is there a way to sprinkle server-side values in separated js? In short, no dynamic js files?
I'm not trying to fix an exact project at this time, I have just been curious about this on past projects.
Thanks...
There are multiple ways to achieve this. One of the ways would be populating your data into a Javascript objects on the HTML page directly.
//myview.cshtml
<script>
var pageData = {
name : '#variable1',
value1: #value1
};
</script>
And, in the javascript file:
//pageUI.js
if (pageData) {
$('#page_tile').html(pageData.name);
}
I am sure you can optimize a whole lot (for example, having a single communication between the server side data and the client side code). At the end of the day, you want to make sure that your javascript code can be resusable.
for example one can do this:
A. have the main .js code read any context-specific parameters from the current window like this (page.js):
!function(window){
var configData = window.MyAppNameConfigData;
// rest app code here..
}(window);
B. the server side script can inject these context-specific data in the page's html like this:
<script>
window.MyAppNameConfigData = {
param1: //..
param2: //..
// etc..
};
</script>
Note if needed make sure that the page.js is enqueued/loaded after the data have been injected/inserted (using a script dependency chain for example)
If it's not "inline" (on the View/Page itself), you could do a Partial View/Page:
Trivial example: _PartialJs.cshtml
$(document).ready(function() {
var foo = "#DateTime.Now.Year";
});
Then in your view:
<script>
#Html.Partial("_PartialJs")
</script>
Renders:
<script>
$(document).ready(function() {
var foo = "2015";
});
</script>
Hth...
I was wondering how to make a requirejs module with multiple files.
e.x. I require one file which then somehow gets multiple files.
I know I could do this:
define([all the other files], function () {
var mod = {},
files = [all the other files];
arguments.forEach(function (i) {
mod.[files[i]] = i;
});
return mod;
});
but I was wondering whether there was a better method?
You want a dynamic list of files(.txt,.tpl,.htm,.json), to avoid a change in JS source code to add more files.
I don't know if is there a way to do that, but you must take care about the time that will take to download all this files. I suggest you to create a json file with all files that you want to download, and iterate through this array of files using ajax to get them.
If you are try to get all module inside a directory, you need to create a js file: <package-all>.js that encapsulate an require([all files],function()); for example.
I believe that this is the only way to solve this.
first, write the modules like this,
define(function(){
return {
'mod-a' : require('modules/mod-a'),
'mod-b' : require('modules/mod-b'),
'mod-c' : require('modules/mod-c')
}
})
then use r.js to optimize the above js to blow one (r.js will combine all module file to one), or, you can write like this directly :
define('modules/mod-a', [], function(){});
define('modules/mod-b', [], function(){});
define('modules/mod-c', [], function(){});
define('mod-all', ['modules/mod-a','modules/mod-b','modules/mod-c'], function(){
return {
'mod-a' : require('modules/mod-a'),
'mod-b' : require('modules/mod-b'),
'mod-c' : require('modules/mod-c')
}
})
now, the modules 'mod-all' is the thing you wanted.
I currently have one large external javascript file that is used on the page. I currently wrap the code in a self-invoking function because I have other sections that are loaded using ajax tabs, so I want to avoid naming clashes with those other external js files.
The code in the file is organized like below. I would like to split some of the code inside the plannerTab namespace into smaller files, yet still have it be part of that namespace.
How could I do this? Or, do you guys recommend a different approach? Thanks!
// Document Ready
$(function ()
{
// initializes table
plannerTab.plannerTable.init();
});
var plannerTab = (function ()
{
// All the code for the page is in here. I would like to extract sections
// from in here and put them into their own external files while still keeping
// the namespacing
}();
Update
How could I separate parts from within the plannerTab variable into smaller external js files, and still maintain that they are part of the plannerTab namespace? A small example below.
// Scope: plannerTab.config - Would like to store configuartion into a separate file
var config = {
selectors: {
tableId: '#plannerTable',
addTaskId: '#AddTask',
editTaskSelector: '#plannerTable .edit',
dateFilterSelector: '#plannerTable_TimeFilter li',
deleteTaskClass: '.delete',
searchFilter: '#plannerTable_filter',
selectedDateFilter: 'selected-dateFilter',
taskCellSelector: '#plannerTable .task-col',
taskClass: '.taskId'
},
urls: {
addTaskFormURL: '/Planner/Planner/LoadAddTaskForm',
editTaskFormURL: '/Planner/Planner/LoadEditTaskForm',
deleteTaskURL: '/Planner/Planner/DeleteTask',
getTasksByDateRangeURL: '/Planner/Planner/GetTasksByDateRange',
viewTaskURL: '/Planner/Planner/ViewTask'
}
};
Look at this example (from google)
<script type="text/javascript">
function importScript(url){
var tag = document.createElement("script");
tag.type="text/javascript";
tag.src = url;
document.body.appendChild(tag);
}
window.onload = function(){
// imports go here
importScript("foo.js"); // example
};
</script>
I'm assuming that plannerTab becomes an object return result of the self executing function. If you need to add properties or methods to that object dynamically, you can take a look at jQuery.extend() http://api.jquery.com/jQuery.extend/
You would need to modify the external JS to use the jQuery extend method to add onto existing properties and methods of plannerTab. As long as you keep plannerTab a global variable, you will continue adding to it as you import more external js files.
If you are using the module pattern to maintain private variables in plannerTab, be sure to test how those values behave once you use jQuery.extend().