custom markdown in user input
Asked Answered
S

1

9

I would like to add a simple markdown to user comments.

When user submits this comment:

I just got [card:Black Lotus] man. POW!

I would like it to be display like this:

I just got Black Lotus man. POW!

but with extra html markup:

I just got <span class="preview" data-card="/cards/card.id">Black Lotus</span> man. POW!

1) I looked at Redcarpet but can't figure out how to add [card:...] markdown to it.

2) or should I just run regexp and replace content before saving it to DB and then sanitize(ActionView::Helpers::SanitizeHelper) span tag before displaying a comment?

Skewness answered 6/2, 2013 at 23:56 Comment(0)
S
9

Answering my own question:

Defining custom renderer and overwriting normal_text method does a job.

class HTMLwithCards < Redcarpet::Render::HTML
  def preprocess(full_document)
    full_document.gsub(/\[card:(.*)\]/) do
      card = Card.find_by_name($1)
      if card
        "<span class='preview' data-card='/cards/#{card.id}'>#{$1}</span>"
      else
        $1
      end 
    end
  end
end

and then you can call it like this:

def markdown(text)
  renderer = HTMLwithCards.new(hard_wrap: true, filter_html: true)
  Redcarpet::Markdown.new(renderer).render(text).html_safe
end
Skewness answered 2/3, 2013 at 23:18 Comment(2)
AFAIK you need to use preprocess instead of normal_text, so I'm editing this. If you know something I'm missing, please correct my correction.Sunfast
@Sunfast Won't using preprocess in this way require you to have filter_html off? I think a solution using normal_text or postprocess would be the way to go here, depending on if you care if your syntax messes up code blocksScleroprotein

© 2022 - 2024 — McMap. All rights reserved.