Gem redcarpet-2.2.2 使用问题

zhaojiahui · 2013年05月07日 · 最后由 zhaojiahui 回复于 2013年05月09日 · 3744 次阅读

Ruby: 2.0.0p0 , Rails: 3.2.13, redcarpet: 2.2.2 application_helper.rb

def markdown(text)                                                                                                     
markdown_render = Redcarpet::Render::HTML.new(:hard_wrap => true, :no_styles => true)
markdown = Redcarpet::Markdown.new(markdown_render, :autolink => true, :no_intro_emphasis => true) 
markdown.render(text).to_html.html_safe   
end 

app/views/questions/new.html.erb

<%= simple_form_for @question do |f| %>
<%= f.input :title, :input_html => { :class => "span6" } %> 
<%= markdown(@question.content) %> 
<%= f.button :submit, :class => 'btn-primary' %> 
<%= link_to 'Cancel', @question.id.blank? ? questions_path : question_path(params[:question]), :class => "btn btn-danger" %>
<% end %>

可是这样就会报错:wrong argument type nil (expected String)<%= markdown(@question.content) %> 改成<%= markdown(@question.content.to_s) %>后又报错:undefined methodto_html' for "":String,然后又将application_helper中的markdown.render(text).to_html.html_safe改为markdown.render(text).html_safe`后,没有了 content 输入框,只有 title 输入框。 求指导。。

方向错了,你应该加个字段 Question#content_html 然后在 post action 里把 markdown 生成好赋进去,最后在 show action 显示 @question.content_html 就可以了。

#1 楼 @luikore 额。不好意思。初学者,不是很看得懂。能否给点示例代码什么的吗?

#2 楼 @zhaojiahui 简单点就是把 markdown(@question.content) 放到 show.html.erb 里...

#3 楼 @luikore 我试过这么做,会报错:undefined methodto_html' for "

qqqqqqqqqq
\nhello world

\n":String`.

#5 楼 @luikore 貌似还真是,我记得我之前试过不行啊。谢谢了!

#6 楼 @zhaojiahui 不过还是好奇的问下现在这个方法和之前你说的加Question#content_html字段有什么优劣。。

#7 楼 @zhaojiahui 如果加个 content_html 字段保存渲染后的内容,就不用每次访问 show 都执行 markdown 渲染了,可以快一点,但代码也会变得复杂点

#8 楼 @luikore 貌似有点明白了。Thnk you~

需要 登录 后方可回复, 如果你还没有账号请 注册新账号