Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails with Underscore.js Templates

Tags:

I was trying to use underscore.js templates for templating in a rails 2.3 app which does not have jammit as an asset packager.

Here is the simple Template:

<script type="text/template" id="q-template">     <div class="current-body">         <span class="q-index"><%= title %></span>         <span class-"q-text"><%= body %></span>     </div> </script> 

Rails tries to parse these as erb variables and throws an ArgumentError. How do I get underscore templates to play nicely with rails in this case? Where am I going wrong?

like image 644
paddle42380 Avatar asked Sep 22 '11 12:09

paddle42380


People also ask

Is underscore JS still used?

Lodash and Underscore are great modern JavaScript utility libraries, and they are widely used by Front-end developers.

How do you use underscore in JavaScript?

Adding Underscore to a Node. Once added, underscore can be referred in any of the Node. js modules using the CommonJS syntax: var _ = require('underscore'); Now we can use the object underscore (_) to operate on objects, arrays and functions.

What is _ template?

The _. template() function is an inbuilt function in the Underscore. js library of JavaScript which is used to compile JavaScript templates into functions that can be evaluated for rendering. Useful for rendering complicated bits of HTML from JSON data sources.

What is underscore min JS?

Underscore. JS is a popular javascript based library which provides 100+ functions to facilitate web development. It provides helper functions like map, filter, invoke as well as function binding, javascript templating, deep equality checks, creating indexes and so on.


1 Answers

Use some other delimiters instead of <%= %>. For example, to use mustache-style brackets {{= }} (interpolate) and {{ }} (evaluate), add this somewhere to your javascript:

_.templateSettings = {     interpolate: /\{\{\=(.+?)\}\}/g,     evaluate: /\{\{(.+?)\}\}/g }; 
like image 113
kulesa Avatar answered Sep 30 '22 12:09

kulesa