Rails 3.1:通过 JavaScript 调用模板

发布于 2024-12-04 18:19:07 字数 462 浏览 1 评论 0原文

我刚刚经历了这个

老rails演员阵容,有一件事它提到的是(显然现在已过时)link_to_function 代码。它提到的一个有趣的片段是:

 link_to_function "Add a Task" do |page|
    page.insert_html :bottom, :tasks, :partial => 'task', :object => Task.new
  end

简而言之,单击“添加任务”链接会将“任务”部分附加到页面,无需使用 ajax。

我熟悉如何在 Rails 3/3.1 中通过 AJAX 和/或手动 javascript 执行此操作,但是如何在不接触 ajax 的情况下即时提取模板部分?

I was just going through this

old rails cast episode, and one thing it mentions is the (now obsolete, apparently) link_to_function code. One interesting snippet it mentions is

 link_to_function "Add a Task" do |page|
    page.insert_html :bottom, :tasks, :partial => 'task', :object => Task.new
  end

In short, clicking the "Add a Task" link appends the "task" partial to the page without ajax.

I'm familiar with how to do this in Rails 3/3.1 via AJAX and/or manual javascript, but how do you pull in a template partial on the fly without touching ajax?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

以为你会在 2024-12-11 18:19:07

它只是简单地将 html 内容存储在 javascript 代码中,并在呈现页面时呈现该内容。因此,当您单击“添加任务”时,部分内容已经在添加任务操作的 javascript 代码中转义了。用firebug看一下页面内容就可以了。

另外,文档显示 instert_html 的原型如下所示:

def insert_html(position, id, *options_for_render)
  content = javascript_object_for(render(*options_for_render))
  record "Element.insert(\"#{id}\", { #{position.to_s.downcase}: #{content} });"
end

因此您可以看到内容实际上是 task 部分,并且它被插入到 javascript 代码中。
我还必须提到,这是一种使用 JavaScript 的侵入性方式。

查看文档

It just simply stores the html content within the javascript code, which it's rendered while the page is rendered. So when you click "Add a task" the partial is already there escaped in the javascript code of the add task action. Just take a look to the content of the page with firebug.

Also the docs shows that the instert_html looks like this for prototype:

def insert_html(position, id, *options_for_render)
  content = javascript_object_for(render(*options_for_render))
  record "Element.insert(\"#{id}\", { #{position.to_s.downcase}: #{content} });"
end

So you can see that the content is actually the task partial, and it's inserted into javascript code.
Also i have to mention that this is an obtrusive way to use javascript.

Take a look at the docs.

栀子花开つ 2024-12-11 18:19:07

我正在经历相同的railscast,我发现这不起作用的原因是因为此方法使用Prototype,默认情况下Rails 3.1不可用。

您可以通过从以下位置安装原型 gem 来实现此功能:

https://github.com/rails/prototype-rails< /a>

I was going through the same railscast, and I figured out the reason why this is not working is because this method uses Prototype, which by default is unavailable with the Rails 3.1 .

You could get this working by installing prototype gem from:

https://github.com/rails/prototype-rails

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文