简体   繁体   中英

Backbone.js micro templating

I have an application, that uses Backbone.js,Jquery,Mustache and PHP as backend.

I have implemented micro-templates from underscore.js, which I currently define in my header-page.

I'm a bit dubious as to how I should organise the templates. Is there any efficient way to organise all templates in files and load them as required?

I use the exact same setup as you. Backbone, jQuery, mustache (for initial page render), and PHP (are you a SlimPHP fan? :-) I'm sure there are many ways to do this but one really great tool you might consider using is require.js.

With require, basically you code your Backbone client-side app as a series of AMD modules. Models, Collections, Views are their own modules that define dependencies with one another. The nature of AMD modules is that all modules are loaded asynchronously. So when your first page loads, only the code necessary to get that page going executes. When you leave the page and go to another, then that code is executed including all the dependencies that code has defined.

The nice thing about require is that it has a plugin that allows you to separate all your HTML code into html files. You simply define which views need those files as dependencies and it imports them as text to be used in the underscore templates.

Once you're ready to go live, you can use require.js' optimize feature to minify and combine all your js scripts + html templates into one file. Bang.

For big projects, a tool like this is pretty nice.

RequireJS

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM