Ideally I want to allow the author to (optionally) insert a marker to specify what to use as the "snippet", if not it would take 250 words, and append "..." - for example..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标记(显示完整文档时可以将其忽略)The marker could be thought of like an EOF marker (which can be ignored when displaying the full document)我正在使用 maruku 进行Markdown处理(RedCloth非常偏向于Textile,BlueCloth非常容易出错,而且我想要一个本机Ruby解析器,该解析器可以将peg-markdown和RDiscount排除在外)I am using maruku for the Markdown processing (RedCloth is very biased towards Textile, BlueCloth is extremely buggy, and I wanted a native-Ruby parser which ruled out peg-markdown and RDiscount)或者(因为Markdown仍然被翻译成HTML),正确地截断HTML是一种选择-尽管最好不要markdown()整个文档,而只是获得前几行.Alternatively (since the Markdown is translated to HTML anyway) truncating the HTML correctly would be an option - although it would be preferable to not markdown() the entire document, just to get the first few lines.所以,我能想到的选项是(按优先顺序排列.)So, the options I can think of are (in order of preference)..在maruku解析器中添加截断"选项,该选项将仅解析前x个字,或直到摘录"标记.编写/查找与解析器无关的Markdown truncate'r编写/查找智能HTML截断功能推荐答案 编写/查找智能HTML截断功能 Write/find an intelligent HTML truncating function http://mikeburnscoder.wordpress中的以下内容. com/2006/11/11/truncating-html-in-ruby/,并进行了一些修改将正确截断HTML,并轻松地允许在结束标记之前添加字符串.The following from http://mikeburnscoder.wordpress.com/2006/11/11/truncating-html-in-ruby/, with some modifications will correctly truncate HTML, and easily allow appending a string before the closing tags.>> 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 endend 这篇关于截断Markdown吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!