Sunday, November 30, 2008

Sharing a partial for both server-side and client-side HTML generation.

Say I have a page that shows a table of items (like a shopping cart), and I want to be able to generate the HTML for this table from the server-side (of course). Let's also say that I want to have client-side javascript be able to dynamically add items to this table without a round-trip to the server, based on data gathered on the client. What I end up with is some HTML code (actually, ERb or Haml) that defines the layout of a row in this table, and a duplicate piece of code in javascript that generates identical HTML. The server-side code uses a nice templating language like Haml to fill in the variable pieces, while the client-side code pieces together HTML embedded in strings concatenated with the dynamic data.

Not very DRY. Not easy to maintain. Not pretty to look at.

So...What's a good solution that allows me to write the HTML once, and have one place to maintain it, while still being able to use it to dynamically evaluate the template based on parameterized data on both the server and client sides?

Below is a solution that I came up with. (And I would love to hear any better ideas).

For brevity, I'll use a very simple HTML structure in these examples, but in practice I have used this with much more complex structure and logic. Here's what our example table looks like:


<table id="items">
<tr>
<td class="name">Shirt</td>
<td class="desc">White short-sleeved shirt</td>
<td class="price">$5.99</td>
</tr>

<tr>
<td class="name">Pants</td>
<td class="desc">Blue pants with zipper</td>
<td class="price">$25.99</td>
</tr>
</table>


Assume we have this built using Haml, and there are two partials: one for the top-level table, and one for an individual row. E.g.:

items_table.haml:

%table#items
- items.each do |item|
= render :partial => 'item_row', :locals => {:item => item}


item_row.haml:

%tr
%td.name= item.name
%td.desc= item.desc
%td.price= item.price


In the client-side javascript in our top-level Haml partial, assume we have some function that gets called from some user input action (like filling out a form and clicking a button). E.g.:


:javascript
var addItem = function(name, desc, price) {
var html =
"<tr>" +
" <td class=\"name\">" + name + "</td>" +
" <td class=\"desc\">" + desc + "</td>" +
" <td class=\"price\">" + price + "</td>" +
"</tr>";
$('items').insert(html); // using prototype.js
};


OK...so this doesn't seem so bad with such a simple example, but imagine that the HTML structure for a table row is something much more complex, with conditionals based on the item, and maybe even usage of additional sub-partials. This maintenance for this becomes a nightmare.

This first thing I am going to do is change the item_rows.haml partial. Instead of having it actually render the item's values, it's going to render template replacement variables using #{...} syntax. Note, these are NOT interpolated in the partial. We'll do that in a separate phase from rendering:

item_row.haml:

%tr
%td.name #{item_name}
%td.desc #{item_desc}
%td.price #{item_price}


Next, let's make a couple helper methods. The first one returns this partial rendered as a string. (I do this because in the real world, this takes a number of parameters, and adding a helper layer makes things easier to manage than always calling render directly). The second one renders this partial and then interpolates the #{...} strings inside it, based on the properties of the item we want to render -- effectively making this equivalent to rendering the original version of this template.

item_helper.rb:

module ItemHelper
# Make ActionController::Base#render_to_string available.
helper_method :render_to_string

def item_row_template
render_to_string :partial => item_row
end

def item_row(item)
# Get the template.
t = item_row_template

# Define the template replacement variables.
item_name = item.name
item_desc = item.desc
item_price = item.price

# Evaluate the template
eval(t.inspect.gsub("\\#", "#"))
end
end


This, of course, means we change the top-level partial to use this new item_row helper, like so:

items_table.haml:

%table#items
- items.each do |item|
= item_row(item)


At this point, we've got a functionally equivalent server-side. But the big benefit is that now the HTML template returned by the item_row_template helper method can also be used to do the same substitutions on the client side, thanks to the handy Template class in prototype.js. The Haml that defines the javascript addItem method now looks like this:


:javascript
var addItem = function(name, desc, price) {
var html = new Template(
'#{escape_javascript(item_row_template)}'
).evaluate({
item_name : name,
item_desc : desc,
item_price : price
});
$('items').insert(html);
};


Now, when the markup for the item row changes, it only needs to change in one place, and both the server-side and client-side benefit from it. This certainly feels more DRY...but also seems like a hefty price to pay in terms of complexity...

Monday, November 17, 2008

Bug in Haml Partial Rendering?

I have stumbled across what I think is a bug in rendering a Haml partial in Ruby on Rails. The issue is that when I use render(:partial => '...', :locals => {...}), and one of the locals I define is a Boolean, it seems that if I pass a value of false, that value erroneously gets converted to nil. This causes a problem with a partial that wants to treat false, true, and nil as meaning different things.

Consider the following example:

I have a simple TestController:

class TestController < ApplicationController
def index
end
end


Then, the haml template for that controller:

!!!
%html
%head
%title haml partial test
%body
%b Rendering a Haml Partial
%br
= render :partial => 'test_haml', :locals => {:flag1 => true, :flag2 => false}

%hr
%b Rendering an RHTML Partial
%br
= render :partial => 'test_rhtml', :locals => {:flag1 => true, :flag2 => false}


Notice that partial renders two partials. One is a haml partial, one is an rhtml partial. The rthml one behaves as I would expect, the haml one does not.

Here is what the haml partial looks like:

- if flag1 == false
flag1 is false
- elsif flag1 == true
flag1 is true
- elsif flag1 == nil
flag1 is nil
- else
= "flag1 is #{flag1.inspect}"

%br
%br

- if flag2 == false
flag2 is false
- elsif flag2 == true
flag2 is true
- elsif flag2 == nil
flag2 is nil
- else
= "flag2 is #{flag2.inspect}"


Here is what the rhtml partial looks like:

<% if flag1 == false %>
flag1 is false
<% elsif flag1 == true %>
flag1 is true
<% elsif flag1 == nil %>
flag1 is nil
<% else %>
flag1 is <%= flag1.inspect %>
<% end %>






<% if flag2 == false %>
flag2 is false
<% elsif flag2 == true %>
flag2 is true
<% elsif flag2 == nil %>
flag2 is nil
<% else %>
flag2 is <%= flag2.inspect %>
<% end %>


Here is what the output looks like:



Notice the discrepancy between the output of the haml partial versus the rhtml partial, with respect to flag2.

This is gonna turn out to be a real drag on a project that I am converting from rhtml to haml that has a number of partials that assume that false means false and not nil.

Anybody out there have any thoughts on this?

Sunday, October 12, 2008

Blogger Syntax Highlighting

Since I intend to post code snippets here, I guess I had better figure out how to format code nicely in my blog. I am using Blogger, and from what I can tell in my vast 2 hours of Blogger experience, they don't have any simple built-in way to do nice code formatting and syntax highlighting.

I found a lot of references on how to use the very cool SyntaxHighlighter. Check out blogs on this topic from developertips and IdeaMonk -- that stuff helped a lot.

However, I think since these posts, the javascript code they describe to fix Blogger-specific issues with automatically-inserted <br/> tags has been rolled into the SyntaxHighlighter code, or is otherwise no longer necessary. Including it seems to break the formatting on my blog -- it was removing too many line breaks and putting all my code on one line. I didn't really dig into why that was the case. I just noticed that by removing the extra javascript code and adding the BloggerMode() call, everything worked out nicely.

So...here's a step-by-step walk-through of what I did to get this working:

Step 1: Get SyntaxHighlighter

  • Download the latest version of SyntaxHighlighter (1.5.1 as of this writing).
  • Uncompress the RAR file (download WinRar if necessary).
  • Place the contents of the scripts and styles directories onto a web server that can serve these files for your blog (more on that later). I put these files all in a flat directory structure in my example.

Step 2: Add SyntaxHighlighter to your template

On Blogger, go to Layout->Edit HTML and add the following code to your template, just before the </head> closing tag:


<link href="http://[YOURSITE]/SyntaxHighlighter.css" rel="stylesheet" type="text/css"/>
<script src="http://[YOURSITE]/shCore.js" type="text/javascript"/>
<script src="http://[YOURSITE]/shBrushCpp.js" type="text/javascript"/>
<script src="http://[YOURSITE]/shBrushCSharp.js" type="text/javascript"/>
<script src="http://[YOURSITE]/shBrushCss.js" type="text/javascript"/>
<script src="http://[YOURSITE]/shBrushDelphi.js" type="text/javascript"/>
<script src="http://[YOURSITE]/shBrushJava.js" type="text/javascript"/>
<script src="http://[YOURSITE]/shBrushJScript.js" type="text/javascript"/>
<script src="http://[YOURSITE]/shBrushPhp.js" type="text/javascript"/>
<script src="http://[YOURSITE]/shBrushPython.js" type="text/javascript"/>
<script src="http://[YOURSITE]/shBrushRuby.js" type="text/javascript"/>
<script src="http://[YOURSITE]/shBrushSql.js" type="text/javascript"/>
<script src="http://[YOURSITE]/shBrushVb.js" type="text/javascript"/>
<script src="http://[YOURSITE]/shBrushXml.js" type="text/javascript"/>


(You can delete the lines for languages you aren't going to use.)

Then, at the bottom of your template, just before the </body> closing tag, add the following code:


<script type="text/javascript">
//<![CDATA[
dp.SyntaxHighlighter.ClipboardSwf = "http://[YOURSITE]/clipboard.swf";
dp.SyntaxHighlighter.BloggerMode();
dp.SyntaxHighlighter.HighlightAll("code");
//]]>
</script>



Step 3: Markup your code snippets

Anywhere you want to stick a piece of code in your blog, put code like:


<pre name="code" class="ruby">
class Foo
def bar
puts "foo bar"
end
end
</pre>


That should give you something that looks like:


class Foo
def bar
puts "foo bar"
end
end


The name of the class you use specifies what language to format the code as, and directly corresponds to the names of those javascript files you included in your template.

What if I don't have a web server for these files?

Unfortunately, as far as I can tell, Blogger doesn't provide any static file storage that you can use to serve up these files. (It sure would be nice if they had them already installed somewhere we could all pull them from.) For a quick-and-dirty, free solution that I am not really happy with, try Google Sites. There is one catch: they don't let you store .js files. Here's what I did with Google Sites:
  • Create a new account and a new site.
  • Once you're in, create a new page called "SyntaxHighlighter", that is a "File Cabinet".
  • Rename all the .js files to end in .sj instead.
  • Update the .css file and all the .sj files to this new file cabinet.
  • Modify all the code in your Blogger template that points to these .js files to end in .sj.
  • From the Google Sites file cabinet, copy the link location to one of the files and use the relevant part of that to fix up all the css and js links in your template.
The main caveat to this approach is that it seems to be really slow. I am using the nice friendly URLs to the files on Google Sites, which all end up using HTTP redirects. It's less than ideal, but it's also quick to setup and free. Once you like the way this stuff works on your blog, you can probably find a better place to host those css and js files.

Caveats


I still have a couple issues that I didn't spend any time figuring out yet:

  • I think if you go back and forth between "Edit Html" mode and "Compose" mode, you may get extra <br/> tags inserted into your code.
  • This seemed to mess up the drag-n-drop layout editor. As far as I can tell, it only messed up the placement of the gadgets in the layout editor, but not the actual functionality, and the gadgets still appear on the blog posts in the correct place.
  • The SyntaxHighlighter, or at least the way I added it to my template, seems to break on IE6. It's way too late to care about IE6 users. Those people don't deserve to suck any more time from web developers than they already have.
  • Shit. I just found out it's broken on Safari too. Looks like its "too many redirects" for the ".sj" files. I am thinking that hosting these files on Google Sites is not such a good idea...