ruby-on-rails – 截断Markdown?
我有一个Rails网站,内容是以降价书写的.我希望显示每个的片段,并附上“阅读更多..”链接.
我该怎么做?简单的截断原始文本将无法正常工作,例如.. >> "This is an [example](http://example.com)"[0..25] => "This is an [example](http:" 理想情况下,我想允许作者(可选)插入一个标记来指定要用作“片段”的内容,如果不是250字,并附加“…” – 例如.. This article is an example of something or other. This segment will be used as the snippet on the index page. ^^^^^^^^^^^^^^^ This text will be visible once clicking the "Read more.." link 标记可以被认为是像EOF标记(当显示完整的文档时可以忽略) 我正在使用maruku的Markdown处理(RedCloth非常偏向纺织品,BlueCloth是非常糟糕的,我想要一个本机的Ruby解析器,排除了peg-markdown和RDiscount) 或者(由于Markdown被翻译成HTML,无论如何)正确地截断HTML将是一个选项 – 尽管最好不要对整个文档进行markdown(),只是为了获得前几行. 所以,我可以想到的选择是(按优先顺序).. >添加一个“truncate”选项到maruku解析器,这将仅解析第一个x字,或直到“摘录”标记. 解决方法
以下从http://mikeburnscoder.wordpress.com/2006/11/11/truncating-html-in-ruby/,通过一些修改将正确地截断HTML,并且容易地允许在结束标签之前附加一个字符串. >> puts "<p><b><a href="hi">Something</a></p>".truncate_html(5,at_end = "...") => <p><b><a href="hi">Someth...</a></b></p> 修改后的代码: require 'rexml/parsers/pullparser' class String def truncate_html(len = 30,at_end = nil) p = REXML::Parsers::PullParser.new(self) tags = [] new_len = len results = '' while p.has_next? && new_len > 0 p_e = p.pull case p_e.event_type when :start_element tags.push p_e[0] results << "<#{tags.last}#{attrs_to_s(p_e[1])}>" when :end_element results << "</#{tags.pop}>" when :text results << p_e[0][0..new_len] new_len -= p_e[0].length else results << "<!-- #{p_e.inspect} -->" end end if at_end results << "..." end tags.reverse.each do |tag| results << "</#{tag}>" end results end private def attrs_to_s(attrs) if attrs.empty? '' else ' ' + attrs.to_a.map { |attr| %{#{attr[0]}="#{attr[1]}"} }.join(' ') end end end (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |