问题
I'm using BlueCloth to create html from markdown from the content my users enter into a textarea like this:
def create
@post = Post.new(params[:post]) do |post|
body = BlueCloth.new(post.body)
post.body = body.to_html
end
...
end
This works great! I get the html stored in the database fine, But how do I show markdown in the textarea when the user edits? I tried:
def edit
@post = Post.find(params[:id])
@post.body = BlueCloth.new(@post.body)
@post.body.text
end
The output in my textarea looks like:
#<BlueCloth:0x10402d578>
回答1:
Bluecloth's documentation isn't very well defined. I'm not sure there's an easy way to convert html => markdown.
However, there's nothing stopping you storing the markdown in your database, and convert it to html as necessary.
If you want html to be the default returned by @post.body, then you could always override the accessor.
class Post < ActiveRecord::Base
...
def body
BlueCloth.new(@body).to_html
end
def markdown
@body
end
end
Now @post.body returns the html version of the markdown. while @post.markdown returns the markdown source.
来源:https://stackoverflow.com/questions/1617093/displaying-markdown-in-my-textarea