Search code examples
ruby-on-railsrubyruby-on-rails-5ruby-on-rails-5.2

how to truncate and add a read more in rails


hey guys i have this piece of code

 <%#=link_to raw page.body%></a></div>
 <div class='col-md-8'>
      <div  class="container">
        <h4><b>   <%= link_to page.title, page_path(page.id)%> </b></h4> 
        <p><%=link_to raw page.body%></p> 
    </div>
    </div>
 <% end %>

i want to truncate the page.body output so after 200 text, it'll truncate it and add a read more button to view the full page. How do i do it please


Solution

  • The ActionView::Helper::TextHelper#truncate might work for that:

    <%= link_to truncate(page.body, length: 200) { link_to 'Read More', '#' } %>
    

    The block passed permits you pass an additional link_to helper which you can make work with JS or any other as you need.