#379 Template Handlers pro
Sep 04, 2012 | 12 minutes | Views
Here I will demonstrate creating two template handlers. One for Ruby which is great for JSON or CSV formats. Another for interpreting Markdown which is useful for informational content.
- Download:
- source codeProject Files in Zip (62.3 KB)
- mp4Full Size H.264 Video (29 MB)
- m4vSmaller H.264 Video (14.4 MB)
- webmFull Size VP8 Video (17.1 MB)
- ogvFull Size Theora Video (33.2 MB)
Resources
Note: In Rails 4 a .ruby
template handler will now be provided by default.
config/initializers/ruby_template_handler.rb
ActionView::Template.register_template_handler(:rb, :source.to_proc)
views/products/index.json.rb
@products.map do |product| { name: product.name, price: number_to_currency(product.price), url: product_url(product), # reviews: product.reviews.map { |r| JSON.parse(render(r)) } # reviews/_review.json.rb } end.to_json
views/products/index.csv.rb
response.headers["Content-Disposition"] = 'attachment; filename="products.csv"' CSV.generate do |csv| csv << ["Name", "Price", "URL"] @products.each do |product| csv << [ product.name, number_to_currency(product.price), product_url(product) ] end end
views/products/show.html.rb
div_for @product do content_tag(:h1, @product.name) + content_tag(:p, number_to_currency(@product.price)) + link_to("Edit", edit_product_path(@product)) end
config/initializers/markdown_template_handler.rb
class MarkdownTemplateHandler def self.call(template) erb = ActionView::Template.registered_template_handler(:erb) source = erb.call(template) <<-SOURCE renderer = Redcarpet::Render::HTML.new(hard_wrap: true) options = { autolink: true, no_intra_emphasis: true, fenced_code_blocks: true, lax_html_blocks: true, strikethrough: true, superscript: true } Redcarpet::Markdown.new(renderer, options).render(begin;#{source};end) SOURCE end end ActionView::Template.register_template_handler(:md, MarkdownTemplateHandler) ActionView::Template.register_template_handler(:markdown, MarkdownTemplateHandler)
views/info/about.html.md
# About Us **Lorem ipsum dolor sit amet, consectetur adipisicing elit,** sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. [Products Listing](<%= products_path %>)