Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><a href="https://stackoverflow.com/questions/395783/truncate-markdown/395814#395814">My answer here</a> should do work. The original question (err, asked by me) was about truncating markdown, but I ended up converting the markdown to HTML then truncating that, so it should work.</p> <p>Of course if your site gets much traffic, you should cache the excerpt (perhaps when the post is created/updated, you could store the excerpt in the database?), this would also mean you could allow the user to modify or enter their own excerpt</p> <p>Usage:</p> <pre><code>&gt;&gt; puts "&lt;p&gt;&lt;b&gt;&lt;a href=\"hi\"&gt;Something&lt;/a&gt;&lt;/p&gt;".truncate_html(5, at_end = "...") =&gt; &lt;p&gt;&lt;b&gt;&lt;a href="hi"&gt;Someth...&lt;/a&gt;&lt;/b&gt;&lt;/p&gt; </code></pre> <p>..and the code (copied from the other answer):</p> <pre><code>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? &amp;&amp; new_len &gt; 0 p_e = p.pull case p_e.event_type when :start_element tags.push p_e[0] results &lt;&lt; "&lt;#{tags.last}#{attrs_to_s(p_e[1])}&gt;" when :end_element results &lt;&lt; "&lt;/#{tags.pop}&gt;" when :text results &lt;&lt; p_e[0][0..new_len] new_len -= p_e[0].length else results &lt;&lt; "&lt;!-- #{p_e.inspect} --&gt;" end end if at_end results &lt;&lt; "..." end tags.reverse.each do |tag| results &lt;&lt; "&lt;/#{tag}&gt;" 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 </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload