In this seventeenth part of an eighteen-part series on the Action Pack library for Rails, you'll learn how and why to escape HTML in templates, and more. This article is excerpted from chapter six of the book Beginning Rails: From Novice to Professional, written by Jeffery Allan Hardy, Cloves Carneiro Jr. and Hampton Catlin (Apress; ISBN: 1590596862).
Handling HTML in Templates with Action Pack (Page 1 of 2 )
Escaping HTML in Templates
You should always escape any HTML before displaying it in your views to prevent malicious users from injecting arbitrary HTML into your pages (which is how cross-site scripting attacks are often carried out). The rule of thumb is that whenever you have data that is provided by the user, you canít trust it blindly. You need to escape it. This includes your model attributes, as well as parameters. Fortunately, escaping is easy to do.
While not technically a Rails helper, ERb provides a utility method to escape entities in HTML called escape_html . Itís aliased to h for short, and itís easy to use. Hereís an example:
While weíre working with the _event partial, letís improve the display of the description field. One of the aforementioned text helpers is the simple_format helper. The simple_ format helper converts text to HTML using simple formatting rules. Two or more consec utive newlines are considered as a paragraph and wrapped in <p> tags. One newline is considered as a line break and a <br /> tag is appended. Weíll also use the sanitize helper to make sure there are no gremlins in the description before we format it. Listing 6-25 shows the additions.
Listing 6-25. Formatting Helpers Added in app/views/events/_event.rhtml
Weíve applied our authentication filters, but we still donít have a way to prevent users from editing or deleting events that belong to other users. To do this, weíll add a method to the Event model that can tell us whether the event in question is owned by the user we pass in. When weíre finished, weíll be able to ask an event whether itís owned by the current user. Open the Event model and add the owned_by? method, as highlighted in bold in Listing 6-26.