konr
konr

Reputation: 2565

How can I keep templates out of /js/?

I'm using RequireJS 2 along with backbone and pals to build the website. The beginning of every view is usually something like this:

define([
    'libs/jquery',
    'libs/underscore',
    'libs/backbone',
    'text!templates/coletas/agendamento.html',
], function(...

My problem is that the last line expects to find the template at js/templates/coletas/agendamento.html, and so this poor programmer ends up having to put non-js files in /js/. Is there a way to avoid that and set the base url to ./templates/ everytime I use the text plugin?

I also cannot use absolute paths, because I know not where my code will end up in the server.

Upvotes: 3

Views: 102

Answers (2)

CamelBlues
CamelBlues

Reputation: 3774

This snippet is from my main.js

require.config({
  paths: {
    loader: 'libs/backbone/loader',
    jQuery: 'libs/jquery/jquery',
    Underscore: 'libs/underscore/underscore',
    Backbone: 'libs/backbone/backbone',
    templates: '../templates'
  }

});

Here is an example require.config that you can use to load in modules like my comment (sorry, I did not realize I had this in my app until I read your comment).

Once configured, then you can access various javascript libraries and your seperate templates directory like so (this snippet is from my js/views/overview/main.js:

define([
  'jQuery',
  'Underscore',
  'Backbone',
  'models/overview',
  'text!templates/overview/main.html'
  ]

Upvotes: 2

jakee
jakee

Reputation: 18566

The directory structure I try to follow with requirejs is

webapp/
  main.js
  index.html
  app.js
  js/ <- your code here
  libs/ <- 3rd party stuff here
  templates/
  styles/
  etc/
  ...

so that the require.js -modules' dependencies are evaluated at the webapp - folder level, allowing you to maintain separation of different kinds of files.

Hope this helps!

Upvotes: 1

Related Questions