Martin
Martin

Reputation: 11336

Inserting generated text into the same line as literal content with Haml

document.write('
- @thumbs.each_with_index do |attachment,index|
  <div><a href="#..."><img src="#..." /></a></div>
');

The code above outputs something like this:

document.write('
<div class="item" style="padding:20;float:left;"><div class="item" style="padding:20;float:left;">
');

Is there any way I can accomplish the same but without the breakline that HAML creates? I need to make it something like this:

document.write('<div class="item" style="padding:20;float:left;"><div class="item" style="padding:20;float:left;">');

Upvotes: 1

Views: 232

Answers (3)

Phrogz
Phrogz

Reputation: 303530

Use string interpolation in your template to inline Ruby code:

document.write('#{@thumbs.map.with_index{ |a,i| '<div>...</div>' }.join}');

For example:

require 'haml'
template = IO.read('tmp.haml')
puts template
#=> document.write('#{ @a.map.with_index{ |n,i| "<div>#{n}-#{i}</div>" }.join }')
@a = %w[a b c]
puts Haml::Engine.new(template).render(self)
#=> document.write('<div>a-0</div><div>b-1</div><div>c-2</div>')

Upvotes: 1

Dutow
Dutow

Reputation: 5668

You can use > and <

For exampel:

%ul<
  - 1.upto(5) do |i|
    %li> asdf

Will output a one line list.

In your case:

document.write('
- 1.upto(5) do |i|
  %div>
    %a{ :href => "#..." }>
      %img{ :src => "#..." }>
);

Upvotes: 1

Christopher Manning
Christopher Manning

Reputation: 4567

Create and use a one_line block helper

Helper

 def one_line(&block)
  haml_concat capture_haml(&block).gsub("\n", '').gsub('\\n', "\n")     
 end

View

- one_line do
  document.write('
  - @thumbs.each_with_index do |attachment,index|
    <div><a href="#..."><img src="#..." /></a></div>
  ');

Upvotes: 2

Related Questions