Peter Boomsma
Peter Boomsma

Reputation: 9806

Render rails form in a template

I'm trying to render a form in a backbone template,

template: _.template(
  '<li><%= form_for :movie, url: movie_path do |f| %><% end %></li>'
),

But it's giving me the following error in the console of Chrome.

Uncaught SyntaxError: Unexpected token : 

It's probably because I'm using erb code in this context, does anyone know a solution?

Upvotes: 0

Views: 172

Answers (1)

Vitaly Stanchits
Vitaly Stanchits

Reputation: 688

I have kind of a feeling this has something to do with the code having " or ' that cause the problem, I suggest using Firebug (Firefox plugin) to debug the code, since it is IMO better suited for debugging HTML and JS than the Chrome console.

Generally it is not that good to have ERB code inside the templating JS, I suggest solving that by doing it the following way:

Do not use default Underscore interpolation, since it is easy to mix it up with ERB code, which you also need but differently. I use:

Backbone.$ = $;  // I have no idea why backbone complains about that stuff, but this thing solves the problem.
_.templateSettings = {
  interpolate: /\$\{\{(.+?)\}\}/g,
  escape: /\%\{\{(.+?)\}\}/g,
  evaluate: /\{\{(.+?)\}\}/g
};  // set template interpolation settings

you can set these options the way you want

Make a normal HTML partial and have the contents inside it wrapped in template code, like this:

<script id="something_template" type="text/template">
  <li><%= form_for :movie, url: movie_path do |f| %><% end %></li>
</script>

note: dont mix up ruby code <%= %> and backbone JS code %{{ }}

Render this partial with javascript, I suggest in the render method of the backbone view class

render: function () {
  $("#container").empty();
  $(_.template($("#something_template").html(), { 
    // variables go here
  })).appendTo("#container");
}

Hope this tip helps you solve your problem. I can only say it works for my projects.

Upvotes: 1

Related Questions