没有RJS的Javascript模板,带有JSON

go *_*mal 4 javascript jquery rjs

关于RJS最方便的一点是它能够渲染部分内容,因此您可以在一个地方拥有所有视图代码:

# 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>
Run Code Online (Sandbox Code Playgroud)

现在我正试图摆脱RJS并让服务器以一个小的,格式良好的JSON而不是大量的JS + HTML进行响应.

有没有办法保持我的部分文件和代码没有重复,并能够通过JS添加新项目而不使用RJS?我已经研究了一些javascript模板引擎,但它们都需要我维护一个单独的ruby部分和一个javacript模板.

Pet*_*tah 8

jQuery 1.4.3将包含tmpl插件(直接集成到jQuery中)请参阅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>
Run Code Online (Sandbox Code Playgroud)