Rails truncate with a 'read more' toggle

lflores picture lflores · Mar 7, 2013 · Viewed 9.2k times · Source

I have a paragraph that I want truncated with the option of clicking "read more" and have it slide open with the rest of the content. The content is coming from a database field. Here's what I have for the truncate:

<%= truncate(@major.glance, :length => 250, :omission => '... Read More')%>

I can't seem to find a way to do this with data pulled from a database. I see a lot of examples using the full text with the text you want to hide in a separate div tag. But, since this content is coming from a database and is dynamic I can't find any information on how to do it.

Answer

jvnill picture jvnill · Mar 7, 2013

You can try the following

<div>
  <% if @major.glance.length > 250 %>
    <%= link_to_function truncate(@major.glance, length: 250), "$(this).parent().html('#{escape_javascript @major.glance}')" %>
  <% else %>
    <%= @major.glance %>
  <% end %>
</div>

or if you prefer to use the Read more link

<div>
  <% if @major.glance.length > 250 %>
    <%= truncate(@major.glance, length: 250) %>
    <%= link_to_function '...Read more', "$(this).parent().html('#{escape_javascript @major.glance}')" %>
  <% else %>
    <%= @major.glance %>
  <% end %>
<div>

UPDATE

Since in Rails 4, link_to_function is deprecated and it is advisable to have non obstrusive js, use the following

<div>
  <% if @major.glance.length > 250 %>
    <%= truncate(@major.glance, length: 250) %>
    <%= link_to '...Read more', '', class: "read-more-#{@major.id}" %>
    <script>
      $('.read-more-<%= @major.id %>').on('click', function(e) {
        e.preventDefault()
        $(this).parent().html('<%= escape_javascript @major.glance %>')
      })
    </script>
  <% else %>
    <%= @major.glance %>
  <% end %>
<div>