简体   繁体   中英

How to properly render a partial template that is using a jQuery plugin?

I am using Ruby on Rails 3.2.2 and the jquery-rails 2.0.2 gem (including the jQuery UI plugin). In order to DRY (Don't Repeat Yourself) my code I am planning to "extract" the jQuery Dialog Widget in a partial template that will be rendered in my application almost the same way; so, I am thinking to implement and render that template by passing some "complex" code (possibly, JavaScript code) throughout the :locals statement... but I have some trouble on how to properly pass that code.

Specifically, I would like to render the template by passing :locals with which "build" / that "populate" some jQuery Dialog Option , Event , Method (see the jQuery UI Official Documentation for more information) as-like, for example, the option title or the event close ( note : it is intended that the "passed" / "builded" / "populated" content is JavaScript code or both JavaScript and Ruby code).

What / how could / should I make to accomplish what I aim to make? Is there some "common" approach or practice?

Here's a simple example. See if this is helpful, and YMMV.

A partial can contain JavaScript and Ruby code as ERB (or HAML, or whatever templating you want to use).

I use the convention of putting shared partials in the directory ./app/views/shared .

Example file ./app/views/shared/_dialog.html.erb :

<!-- typical jQuery dialog box creator -->
<script>
  $(function() {
    $( "#dialog" ).dialog();
  });
</script>

<!-- typical dialog with Ruby ERB for title and message -->
<div id="dialog" title="<%= title %>">
  <p><%= message %></p>
</div>

To call the partial from your view page:

<h1>My Page</h1>
<%= render :partial => "shared/dialog",
    :locals => { :title => :"Hello", :message => "World" } %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM