Rails truncate with a 'read more' toggle

孤街醉人 提交于 2019-11-30 17:53:00

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>

I know I am joining this conversation a bit late. I have been tackling the same issue, trying the solution above, which works just fine. However, SEO wise content that has been hidden wasn't indexed by search engines. I checked in Lynx too and the link can not be followed (obviously). So settled for the this solution by Jed Foster | readmore.js - lynx can read it properly and now I am waiting for the SE index to update and see if I can find myself in the search results. Just in case someone is in a similar situation...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!