Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

custom markdown in user input

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?

like image 829
Kocur4d Avatar asked Feb 06 '13 23:02

Kocur4d


People also ask

How do I put HTML code in Markdown?

in HTML will appear as <div class=Heading 1> Markdown also allows for raw HTML. There is no need to put any syntax around the code, but it needs to stand alone in the source document with no content above or below. A good example of using raw HTML in a Markdown document is when embedding a Youtube video.

What is Markdown input?

The Markdown field enables users to input text in markdown format in an entry. Markdown text is an easy-to-read text that is marked with certain tags or formatting instructions.

How do you add a code block in Markdown?

Code Blocks To produce a code block in Markdown, simply indent every line of the block by at least 4 spaces or 1 tab. For example, given this input: This is a normal paragraph: This is a code block. A code block continues until it reaches a line that is not indented (or the end of the article).


1 Answers

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
like image 88
Kocur4d Avatar answered Oct 03 '22 19:10

Kocur4d