我有一个 Rails 站点,其中的内容是用 markdown 编写的。我希望显示每个片段,并带有“阅读更多..”链接。
我该怎么做?简单截断原始文本将不起作用,例如..
>> "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 非常偏向于 Textile,BlueCloth 非常有问题,我想要一个本地 Ruby 解析器,它排除了 peg-markdown 和 RDiscount)
或者(因为 Markdown 无论如何都会被翻译成 HTML)正确截断 HTML 将是一个选项 - 尽管最好不要 markdown()
整个文档,只是为了获得前几个行。
所以,我能想到的选项是(按优先顺序)..
- 向 maruku 解析器添加一个“截断”选项,它将只解析前 x 个单词,或者直到“摘录”标记。
- 编写/查找与解析器无关的 Markdown truncate'r
- 编写/查找智能 HTML 截断函数
最佳答案
- Write/find an intelligent HTML truncating function
以下来自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
关于ruby-on-rails - 截断 Markdown ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/395783/