Despite the fact that ive accepted a different answer, I went ahead and fulfilled this specific requirement in several ways. I published the best and simplest method that I found, which, in my opinion, will be useful for people who do not want to use any template mechanisms, such as a puppet or so.
Using Masters and Underscore:
Folder structure
The folder structure may be as follows:
Root: ββββcss ββββjs β ββββrouter.js β ββββmodel.js β ββββview.js β ββββconfig.js ββββtemplates β ββββhome.html β ββββlogin.html β ββββregister.html ββββimages ββββindex.html
Base template
You will need a basic template (index.html) in which you will display different templates. This ensures that the overall html content, such as a listener, footer, navigation menu, etc., does not load every time a new page is displayed, and thereby greatly increases the page loading speed.
The sample structure may be as follows:
<html> <head> </head> <body> <div class="template_body"> <div class="header"> </div> <div class="content" id="template"> </div> <div class="footer"> </div> </div> </body> </html>
Note. Please note that you can choose the structure of the template as you want. What I use is more general so that everyone can relate to it easily.
View
In your view, you can display a specific template of the base template as follows:
var LoginView = Backbone.View.extend({ el: "#template",//Container div inside which we would be dynamically loading the templates initialize: function () { console.log('Login View Initialized'); }, render: function () { var that = this; //Fetching the template contents $.get('templates/login.html', function (data) { template = _.template(data, {});//Option to pass any dynamic values to template that.$el.html(template);//adding the template content to the main template. }, 'html'); } }); var loginView = new LoginView();
Please note that the el tag is very important.
To pass values ββfor viewing, just pass them like this:
var data_to_passed = "Hello"; $.get('templates/login.html', function (data) { template = _.template(data, { data_to_passed : data_to_passed });
And in the template:
<%=data_to_passed;%>//Results in "Hello"
You can pass an array, an object, or even a variable.
Hope this was helpful. Greetings