views:

62

answers:

4

I find myself frequently writing code like this in the HTML HEAD and other places:

<% if @canonical_url %>
  <link rel="canonical" href="<%= @canonical_url %>"/>
<% end %>

I then set the variable in the controller if it's appropriate.

Is there any way of writing the equivalent on one line, or maybe a different way of organizing the code?

A: 

Ok, I came up with this solution. In the template:

<%= show_if('<link rel="canonical" href="$1"/>', @canonical_url) %>

And then the helper method:

#
# Return the template text if the variable has a value.
#
def show_if(template, variable)
  if variable
    template.gsub('$1', variable)
  else
    ''
  end
end
Dogweather
+1  A: 

I'd need a bit more context to determine what it is that you're trying to do. Given the information that you provide, I would recommend taking a look at the canonical-url plugin for Rails.

Patrick Reagan
A: 
def if_value(value, &block)
  if value
    concat(capture(value, &block))
  end
end

<% if_value(@canonical_url) do |value| %>
  <link rel="canonical" href="<%= value %>"/>
<% end %>
Simone Carletti
+2  A: 

Sorry for the double answer, SO will only let me post one URL.

Alternatively, your problem might be solved by using content_for in your views where you want to have this content appear in your layout.

Patrick Reagan