Vidar 22 October 2009
Simple format and auto link images

I used to use Redcloth and textilize for all my apps until I found out that it allows too much and I wanted something simpler. The built-in simple_format would convert all newlines to break and paragraph tags, but I needed to be able to insert links and images as well. The auto_link builtin text helper in rails converts all links starting with http or www to clickable links. But what about the images? I needed a way to check if the link was to an image, convert it to an image tag and also extract the height and the width of the image to avoid the web-page jumping around when loading big images.

First I tried doing it server side with regular expressions but I couldn’t find a good way of extracting the image height and width, also I would have to redo it every time the page was edited. So I just used Javascript. This is how I did it using JQuery.

On the server to prepare the text and autolink.

def self.htmlify(text)
    html = strip_tags(text)
    html = auto_link(html, :link => :urls, :href_options =>{:target => '_blank'})
    html = simple_format(html)
    if html[0..2] == "<p>" then html = html[3..-1] end
    if html[-4..-1] == "</p>" then html = html[0..-5] end
    return html
  end

On the client

$.fn.showImageLinks = function(){
  links = $(this).find("a").filter(function(){return this.href.match(/(png||gif||jpe?g||bmp)$/i)});
  $.each(links, function(index, element){
    var image = $("<img>").attr("src", element.href);
    image.attr({height: image[0].height, width: image[0].width});
    $(element).replaceWith(image);
  });
  return $(this);
}
// replace core with the element containing the links
$('#core').showImageLinks();

1. Find all the links ending with image extensions.
2. Replace each of them with image tags.
3. Done. Remove RedCloth/Textile. It’s not worth it.

The image[0].width and image[0].height magically contains the image info after you set the src attribute.

 

« Back to posts Write a new comment

Feed-icon 0 Comments

Textilized formatting

How to use the text area
_a phrase_ a phrase
*a phrase* a phrase
_*a phrase*_ a phrase
"Link":http://link.com Example link
Complete reference