Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this the correct way to display/concatenate text using Haml?

I'm very new to Ruby on Rails, and even newer to Haml, i started using it 2 hours ago. So i'm following a Ruby on Rails tutorial and decided to use Haml on the views, but i'm not sure if this is the correct way to display things (it feels kinda weird). Could someone enlighten me? :)

%h1= "About Us"
%p
  =link_to 'Ruby on Rails Tutorial','http://railstutorial.org' 
  &= 'is a project to make a book and screencasts to teach web development with'
  &= link_to 'Ruby on Rails', 'http://rubyonrails.org'
  &= '. This is the sample application for the tutorial.'

I've tried this too:

:ruby
   first_link = link_to 'Ruby on Rails Tutorial','http://railstutorial.org' 
   second_link = link_to 'Ruby on Rails', 'http://rubyonrails.org'

%h1= "About Us"
%p
  = first_link
  &= 'is a project to make a book and screencasts to teach web development with'
  &= second_link
  &= '. This is the sample application for the tutorial.'
like image 654
Jorge Guberte Avatar asked Jun 19 '11 04:06

Jorge Guberte


People also ask

How to combine two strings in Ruby?

You can use the + operator to append a string to another. In this case, a + b + c , creates a new string. Btw, you don't need to use variables to make this work.

How to append to a string in Ruby?

In Ruby, we use #concat to append a string to another string or an element to the array. We can also use #prepend to add a string at the beginning of a string.


1 Answers

You can use #{} to wrap ruby code within a block of text, and if you just want text (like in your %h1) you don't need to use =.

%h1 About Us
%p
  #{link_to 'Ruby on Rails Tutorial','http://railstutorial.org'} is a project to make a book and screencasts to teach web development with #{link_to 'Ruby on Rails', 'http://rubyonrails.org'}. This is the sample application for the tutorial.

If you want to break the line so that its easier to handle in your editor, make sure you indent each line the same amount, and don't split in the middle of a Ruby function:

%h1 About Us
%p
  #{link_to 'Ruby on Rails Tutorial','http://railstutorial.org'} is a project to make a
  book and screencasts to teach web development with #{link_to 'Ruby on Rails', 'http://rubyonrails.org'}.
  This is the sample application for the tutorial.
like image 162
matt Avatar answered Sep 28 '22 17:09

matt