Transforming Plain Text to HTML






Transforming Plain Text to HTML

Problem

You want to add simple markup to plaintext and turn it into HTML.

Solution

Use RedCloth, written by "why the lucky stiff" and available as the RedCloth gem. It extends Ruby's string class to support Textile markup: its to_html method converts Textile markup to HTML.

Here's a simple document:

	require 'rubygems'
	require 'redcloth'

	text = RedCloth.new %{Who would ever write "HTML":http://www.w3.org/MarkUp/
	markup directly?

	I mean, _who has the time_? Nobody, that's who:

	|_. Person |_. Has the time?        |
	|   Jake   |     No                 |
	|  Alice   |     No                 |
	|  Rodney  | Not since the accident |
	}

	puts text.to_html
	# <p>Who would ever write
	# <a href="http://www.w3.org/MarkUp/"><span class="caps">HTML</span></a>
	# markup directly?</p>
	#
	# <p>I mean, <em>who has the time</em>? Nobody, that&#8217;s who:</p>
	#
	# <table>
	#  <tr>
	#   <th>Person </th>
	#   <th>Has the time?        </th>
	# </tr>
	# …

The Textile version is more readable and easier to edit.

Discussion

The Textile markup language lets you produce HTML without having to write any HTML. You just add punctuation to plain text, to convey what markup you'd like. Paragraph breaks are represented by blank lines, italics by underscores, tables by ASCII-art drawings of tables.

A text-based markup that converts to HTML is very useful in weblog and wiki software, where the markup will be edited many times. It's also useful for hiding the complexity of HTML from new computer users. We wrote this entire book using a Textile-like markup, though it was converted to Docbook instead of HTML.

See Also



 Python   SQL   Java   php   Perl 
 game development   web development   internet   *nix   graphics   hardware 
 telecommunications   C++ 
 Flash   Active Directory   Windows