Where in the Rails structure should I place Backbone templates?

I am a rails developer trying to learn Backbone, and then I ran into this problem: since Underscore patterns contain characters like <%=%> , I think patterns cannot be included in erb files, so it's good that the rails are partial for each individual template? And what extension should there be?

+6
source share
3 answers

You can avoid erb characters by using two % in the opening tag and put your base patterns in the rail views:

 <script type='text/template' id="my-template'> <%%= name %> </script> 

will display the following on your page:

 <script type='text/template' id="my-template'> <%= name %> </script> 

Putting your Backbone templates right on your rail views is the best option when you are trying to learn. You are already struggling with new concepts, there is no need to add another obstacle.

+12
source

Starting with Rails 3.1, it provides two things that make working with Backbone templates easier: an asset pipeline and an automatic JST structure (JavaScript Template).

Create a directory in the app/assets folder named templates . This directory is automatically selected by the asset pipeline.

Then specify the files in this directory with the jst extension and the type of the created ejs template (built-in javascript). You can even nest them in directories. For instance:

 app/assets/templates/my_template.jst.ejs app/assets/templates/bookmarks/show.jst.ejs 

The asset console also allows you to use other template languages, such as the built-in coffeescript, mustache, rudders, etc., simply by changing the file extension (and including any gems needed).

Now, to reference your JST templates in Backbone views, simply use the file name path:

 var Bookmark = Backbone.View.extend({ template: JST['bookmarks/show'], render: function() { this.$el.html(this.template(this.model.attributes)); return this; } }); 

You may need to add this line to your application.js :

 // require_tree ../templates 

Here is a good article that explains all this in a bit more detail: http://www.bigjason.com/blog/precompiled-javascript-templates-rails-3-1

+4
source

Where should you place your Masters templates? I would say nowhere. I believe that in most Rails applications, the server should be responsible for all HTML rendering, while client-side JavaScript should simply be responsible for inserting this rendered HTML into the DOM. Among other things, it makes the I18n easier.

An exception would be if Rails is simply used as a lightweight backend for an application that runs mainly on the client side (although in this case you can use Sinatra or something instead). In this case, Rails should probably do nothing, and JS does all the rendering.

Pay attention to the fundamental principle. Either the server should be responsible for the entire rendering, or for the client. Separating it will make life harder.

-3
source

Source: https://habr.com/ru/post/901517/


All Articles