【问题标题】:Using Rails' view helpers inside javascript templates在 javascript 模板中使用 Rails 的视图助手
【发布时间】:2012-11-13 12:30:44
【问题描述】:

我希望能够在我的 javascript 模板中使用一些 rails 的视图和表单助手,例如 <%= image_tag .. %><%= select_tag .. %>。我读到this thread 建议将erb 预渲染为某个javascript 变量中的字符串,然后从模板中调用它(它必须在调用js 模板之前可用)。所以我可以这样做:

view_helpers.js.erb

<script type="text/javascript">
  var ViewHelpers = {
      CountrySelect: "<%= select_tag "person[country_id]", options_from_collection_for_select(Country.all, "name", "id"), :prompt => '-Country-' %>"
  };
</script>

然后从我的生态模板中调用它(稍后渲染):

edit_person.jst.eco

...
<p>
  <label for="person_country_id">Country</label>
  <%= ViewHelpers.CountrySelect %>
</p>
...

但是,我似乎无法将其作为视图的一部分或使用资产管道加载:

资产管道:application.js

(保存在 app/assets/javascripts/views/people/view_helpers.js.erb)

//= require ./views/people/view_helpers

ERB 模板:views/people/index.html.erb

(保存在 app/views/people/view_helpers.js.erb)

<%= render :template => 'people/view_helpers' %>

我是完全错误地处理这个问题还是我错过了什么?谢谢。

【问题讨论】:

  • 你读过这个答案吗? stackoverflow.com/questions/7451517/…我认为有一些关于您的问题的有用信息。
  • 不,错过了那个,它似乎可以解决问题 - 我错过了 ActionView::Helpers 的包含。谢谢!

标签: javascript ruby-on-rails template-engine form-helpers eco


【解决方案1】:

是的,这是可能的。你甚至可以将它与部分一起使用:

update_js.js.erb:

$('#element').html('<%= escape_javascript(render(:partial => @partial, :locals => {:my_var => @item })) %>');

在控制器中你应该有格式js:

   respond_to do |format|
      format.js do
        render :update_js do |page|
          page.replace_html "element", :partial => @partial
        end
      end
    end

如果您想使用 AJAX 调用此 js,只需将 :remote =&gt; true 传递给您的链接

<%= link_to 'replace content', item_path(@item), :remote => true %>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多