A little Haml tutorial on how to render different formats


Suppose you have a Model called Article that contains a text field and a format field.

You would like to use haml, textile or HTML to edit your Article from the admin interface.

  create_table "articles", :force => true do |t|
    t.string   "title"
    t.text     "body"
    t.string   "formatting_type", :limit => 20, :default => "HTML"
  end

app/models/article.rb

It’s quite simple. All you have to do is to add this helper in your application_helper.rb

  def print_formated(type,text)
    case type
    when "HTML"
      text
    when "Plain Text"
      h text
    when "HAML"
      Haml::Engine.new(text).render
    when "Syntaxy"
      Syntaxi.line_number_method = 'none'
      Syntaxi.new(text).process
    when "Textile"
      RedCloth.new(text).to_html
    end
  end

In your views/articles/_form.haml add the select field.

  = label :article, :formatting_type
  = select(:article, :formatting_type, Article::FORMATTING_TYPES.collect {|p| p }, { :include_blank => false })

Then in the Show view (articles/show.haml)

 
.article
  .title
    %h1
      = h @article.title
  .body
    = print_formated(@article.formatting_type, @article.body)

that’s pretty much it.
:)

VN:F [1.8.3_1051]
Rating: 8.0/10 (4 votes cast)
VN:F [1.8.3_1051]
Rating: +1 (from 1 vote)
A little Haml tutorial on how to render different formats8.0104
  1. No comments yet.
(will not be published)