Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/419.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/56.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何从RubyonRails助手方法返回javascript?_Javascript_Ruby On Rails_Helpers - Fatal编程技术网

如何从RubyonRails助手方法返回javascript?

如何从RubyonRails助手方法返回javascript?,javascript,ruby-on-rails,helpers,Javascript,Ruby On Rails,Helpers,我有一个便笺模型,它可以包含图像链接附件(linktype=“image”或一些文本(linktype=“text)。当我显示便笺时,显示方法会根据链接类型而改变。例如: <% @notes.each do |q| %> <h2 class="title"><%= q.name %></h2> <% if q.linktype == "other"%> <script type="text/java

我有一个便笺模型,它可以包含图像链接附件(linktype=“image”或一些文本(linktype=“text)。当我显示便笺时,显示方法会根据链接类型而改变。例如:

<% @notes.each do |q| %>
    <h2 class="title"><%= q.name %></h2>
    <% if q.linktype == "other"%>
        <script type="text/javascript">some javascript</script>
    <% elsif q.linktype == "text"%>
        <%= q.text %>
    <% elsif q.linktype == "image"%>
       <img src="<%= q.link %>" />
    <% end %>
<% end %>

一些javascript
" />
我必须在我的站点中的几个不同视图中显示注释,因此我不必多次重复查看代码,而是希望将其放在一个位置,并从不同的视图中引用

我最初的想法是将显示代码放在助手中,如下所示:

<% @notes.each do |q| %>
    note_display(q.linktype, q.link)
<% end %>

注释显示(q.linktype,q.link)

但有些显示涉及javascript(第一个代码块中的第4行)。即使我需要它来返回javascript,我仍然可以使用helper方法吗?如果需要,我该怎么做?谢谢阅读。

javascript没有什么特别之处,您可以从helpers返回它,就像返回其他html内容一样。我唯一建议的是对类似

image_tag(q.link)
javascript_tag("some javascript")
content_tag("h2", q.name, :class => "title")

就ERB而言,JavaScript只是字符串内容,就像模板呈现的任何其他内容一样。因此,您的助手方法可以构造并返回字符串:

def note_display(note)
  content = ''
  content << content_tag('h2', h(note.name), :class => 'title')
  if note.linktype == 'other'
    content << javascript_tag("some javascript")
  elsif note.linktype == 'text'
    content << h(note.text)
  elsif note.linktype == 'image'
    content << image_tag(note.link)
  end  
  content
end
def note_显示(注释)
内容=“”
内容(标题)
如果note.linktype==“其他”
内容
<% @notes.each do |n| %> 
  <%= note_display(n) %>
<% end %>