简体   繁体   English

如何正确渲染使用jQuery插件的部分模板?

[英]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). 我正在使用Ruby on Rails 3.2.2和jquery-rails 2.0.2 gem(包括jQuery UI插件)。 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; 为了干燥(不要重复自己的代码)我的代码,我打算在部分模板中“提取” jQuery Dialog Widget ,该模板将在我的应用程序中以几乎相同的方式呈现。 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. 因此,我正在考虑通过在:locals语句中传递一些“复杂”代码(可能是JavaScript代码)来实现和呈现该模板,但是我在如何正确传递该代码方面遇到了一些麻烦。

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). 具体来说,我想通过传递:locals来呈现模板,例如,通过:locals传递“构建” / “填充”一些jQuery Dialog OptionEventMethod (有关更多信息,请参见jQuery UI官方文档 )。选项title或事件close注意 :“通过” /“构建” /“填充”的内容是JavaScript代码或JavaScript和Ruby代码)。

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. 看看这是否有帮助,以及YMMV。

A partial can contain JavaScript and Ruby code as ERB (or HAML, or whatever templating you want to use). 部分可以包含JavaScript和Ruby代码作为ERB(或HAML,或您要使用的任何模板)。

I use the convention of putting shared partials in the directory ./app/views/shared . ./app/views/shared将共享的部分放在目录./app/views/shared

Example file ./app/views/shared/_dialog.html.erb : 示例文件./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" } %>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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