Search code examples
ruby-on-railsrubyruby-on-rails-3link-toredcarpet

Combining truncate with Redcarpet markdown in Rails: Links don't work


I'm using Redcarpet for syntax highlighting in my Rails blog application.

In my posts/index.html.erb, I want to truncate the blog posts in order to preview the first few sentences (or paragraph). The user should be able to click on "read more" at the end of the truncated post to read the whole blog post. Unfortunately the "read more" link is not working with Redcarpet (when I don't use my markdown method (see below) the link is working fine). How can I fix that? Do I have to use other options in Redcarpet?

My markdown method in /helpers/application_helper.rb using Redcarpet:

def markdown(content)
  renderer = HTMLwithPygments.new(hard_wrap: true, filter_html: true)
  options = {
    autolink: true,
    no_intra_emphasis: true,
    disable_indented_code_blocks: true,
    fenced_code_blocks: true,
    lax_html_blocks: true,
    strikethrough: true,
    superscript: true
  }

  Redcarpet::Markdown.new(renderer, options).render(content).html_safe
end

/views/posts/index.html.erb

<%=  markdown (truncate(post.content, 
                        length: 600, 
                        separator: ' ',
                        omission: '... ') {
                        link_to "read more", post 
               }) %>

By the way: I am looping through the @posts variable, so "post.content" gives me the content of one post and "post" gives me the post's path.

The "read more" text is showing up but you cannot click on it. When I leave the "markdown" method out, the "read more"-link is working fine.

How can I create the link with my "markdown"-method?


Solution

  • That link isn't Markdown though, it's HTML. Maybe change it to Markdown?

    <%= markdown(truncate(post.content, length: 600,
                          separator: ' ', omission: '... ') {
                 "[read more](#{post_path(post)})"
        }) %>
    

    Change post_path to something appropriate if that's not right.