Zack Shapiro
Zack Shapiro

Reputation: 6998

Rendering markdown with Slim/Rails from an instance var

I'm having trouble getting Slim to render my markdown:

div.container
    div.row
        div.col-md-8.job_description
            markdown: 
                = @listing.job_description

That just renders the string

This is an h1 ## h2 ### h3 > this is a quote * hello * goodbye foo

No line breaks or anything (which are contained in the actual string)

How do I get this to render properly? Thanks!

Upvotes: 2

Views: 633

Answers (3)

Mitch Aston
Mitch Aston

Reputation: 21

Rendering Markdown out of a variable in this way isn't possible, as Slim first renders the Markdown (or any other embedded engine language) and only after that interpolates the variable contents.

It makes sense that it would work this way as Slim's embedded engine tags are intended as a way of including different languages in-line so you can read them there. If the markdown isn't included in literal form in the template, there's no advantage to using the embedded engine over simply rendering the Markdown before you pass it to Slim (as HTML, and using '==' to prevent further processing by Slim).

I think, also, that it's set up like this because it's intended to provide and easy way for interpolating text into Markdown - which doesn't itself have a means of interpolation - within the same template as everything else.

The helper Iceman suggests is a nice way to do it. I'd probably call it outside of the template, but that's just because it's my personal preference to do as little as possible inside the template.

Upvotes: 2

Eyeslandic
Eyeslandic

Reputation: 14900

I gave up on using markdown: in slim, had tried everything.

I ended up creating this helper, place it in just any file in app/helpers

def markdown(content)
  return '' if content.blank?
  markdown = Redcarpet::Markdown.new(Redcarpet::Render::XHTML, autolink: true, space_after_headers: true)
  sanitize(markdown.render(content)).html_safe
end

And then in a view

= markdown @listing.job_description

You will of course have to install the redcarpet gem.

gem 'redcarpet'

Upvotes: 4

seancdavis
seancdavis

Reputation: 2821

Looks like your markdown content is not indented under markdown:, so it won't be processed by markdown.

It should look more like this:

div.col-md-8.job_description
  markdown: 
    = @listing.job_description

See this section of the docs for more information.

Upvotes: 0

Related Questions