One of the most convenient things about RJS is its ability to render a partial so you have all your view code in one place:
# task/index.html.erb
<ul id="task_list">
<%= render :partial => 'task', :collection => @tasks %>
</ul>
# task/_task.html.erb
<li>
<% if task.is_completed %>
<%= task.name %> - <%= task.completed_date %>
<% else %>
<%= task.name %> - UNCOMPLETED
<% end %>
...
</li>
Now I'm trying to move away from RJS and have the server respond in a small, nicely-formatted JSON instead of a huge chunk of JS + HTML.
Is there a way to keep my partial file and code as is without duplication and be able to add new items to the task list via JS without using RJS? I've looked into some of the javascript templating engines, but they all require me to maintain a separate ruby partial and a javacript template.
jQuery 1.4.3 will include the tmpl plugin (directly intergrated into jQuery) See http://api.jquery.com/jquery.tmpl/
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="http://nje.github.com/jquery-tmpl/jquery.tmpl.js"></script>
</head>
<body>
<ul id="movieList"></ul>
<script>
var movies = [
{ Name: "The Red Violin", ReleaseYear: "1998" },
{ Name: "Eyes Wide Shut", ReleaseYear: "1999" },
{ Name: "The Inheritance", ReleaseYear: "1976" }
];
var markup = "<li><b>${Name}</b> (${ReleaseYear})</li>";
/* Compile the markup as a named template */
$.template( "movieTemplate", markup );
/* Render the template with the movies data and insert
the rendered HTML under the "movieList" element */
$.tmpl( "movieTemplate", movies )
.appendTo( "#movieList" );
</script>
</body>
</html>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With