views:

43

answers:

2

In Rails, you can create an anchor tag that spans multiple lines doing something like the following:

<% link_to target_url_path do %>
    <span class="title">Example</span>
    <span class="excerpt">Neque porro quisquam est qui dolorem ipsum...</span>
    <%= image_tag 'example.png', :class => 'thumbnail' %>
<% end >

I'm wondering how I can set a value using a similar approach. In essence, something like:

<% my_variable = do %>
    <span class="title">Example</span>
    <span class="excerpt">Neque porro quisquam est qui dolorem ipsum...</span>
    <%= image_tag 'example.png', :class => 'thumbnail' %>
<% end >

Edit: in case anyone is curious why I'm asking, it's because facebox_link_to doesn't appear to allow you to use the do syntax like link_to does.

A: 

This is effectively rendering an inline template. You can use render :inline for this:

<% my_variable = render :inline => <<-EOS
<span class="title">Example</span>
<span class="excerpt">Neque porro quisquam est qui dolorem ipsum...</span>
#{image_tag 'example.png', :class => 'thumbnail'}
EOS
%>

Hope this helps!

Richard Cook
Please, don't do that. You are killing the MVC pattern!
Simone Carletti
A helper, as you suggested, is the way forward. This is my literalist answer to the question.
Richard Cook
+5  A: 

I don't really know what you want to do, however you can use the #tap pattern.

<% my_variable.tap do |variable| %>
  <span class="title">Example</span>
  <span class="excerpt">Neque porro quisquam est qui dolorem ipsum...</span>
  <%= image_tag 'example.png', :class => 'thumbnail' %>
<% end %>

If instead you want to assign a chunk of code to a variable, then you are doing it wrong because views shouldn't set variables in that way.

Instead, use an helper.

Simone Carletti
Can you provide a link to the `tap` pattern? I'm interested in reading more about this. Thanks!
Richard Cook
I tried this and it didn't work: `syntax error, unexpected kENSURE, expecting kEND`
Matt Huggins
http://ruby-doc.org/core-1.9/classes/Object.html#M000191 Also read http://bit.ly/aYgkKe for Rails 3.0
Simone Carletti
Also counter to the MVC pattern, or am I missing something? Thanks for the `tap` link. +1
Richard Cook
@Matt On which line? Which Ruby version?
Simone Carletti
ruby 1.8.7 (2009-06-12 patchlevel 174) [universal-darwin10.0]
Matt Huggins
This solution works for me on Ruby 1.8.7 (Ubuntu 8.04).
Richard Cook
Okay, so I had to define `my_variable` first with any garbage data to make sure it's declared. It worked after that.
Matt Huggins
Tap is a 1.9 feature iirc
Chuck Vose
It was backported to 1.8.7 (which is the minimum version for Rails 3).
Simone Carletti