3

I have a Note model, which can contain have either an image link attachment (linktype = "image" or some text (linktype = "text). When I display the notes, the method of display changes depending on the linktype. An example is:

<% @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 %>

I have to display the notes in a few different views in my site, so rather than have to repeat the viewing code multiple times, I want to have it in one place and refer to it from different views.

My initial thought was to put the display code in a helper, something like this:

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

But some of the displaying involves javascript (line 4 in first code block). Can I still use a helper method, even though I would need it to return javascript? If so, how do I do it? Thanks for reading.

2 Answers 2

10

There's nothing special about javascript, you can return it from helpers as you would return other html content. The only thing I would suggest is to use helpers for tags like

image_tag(q.link)
javascript_tag("some javascript")
content_tag("h2", q.name, :class => "title")
Sign up to request clarification or add additional context in comments.

Comments

3

As far as ERB is concerned, JavaScript is just string content like anything else rendered by a template. So your helper method can just construct and return a string:

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

You can use this helper method using:

<% @notes.each do |n| %> 
  <%= note_display(n) %>
<% end %>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.