HAML和迭代的XML

时间:2010-12-20 21:21:56

标签: ruby sinatra haml

我正在尝试生成XML文件。我有一些标签在数字上重复如下:

# necessary XML namespace and metadata stuff...

%img{:src => "Foo002.jpg#full"}/
%img{:src => "Foo003.jpg#full"}/
%img{:src => "Foo004.jpg#full"}/
%img{:src => "Foo005.jpg#full"}/
# and so on for a few hundred lines

%img{:src => "Foo435.jpg#full"}/

我给了“Foo”和结尾数字(在这种情况下是435)作为参数。我如何告诉HAML这样做?

由于

编辑:忘记提及,前导零很重要。

1 个答案:

答案 0 :(得分:4)

- 2.upto(435) do |n|
  %img{:src => "Foo%03d.jpg#full" % n}

- (2..435).each do |n|
  %img{:src => "Foo%03d.jpg#full" % n}

证明:

phrogz$ haml
!!! XML
%root
  - 2.upto(10) do |n|
    %img{ src:"Foo%03d.jpg" % n }
^D

<?xml version='1.0' encoding='utf-8' ?>
<root>
  <img src='Foo002.jpg' />
  <img src='Foo003.jpg' />
  <img src='Foo004.jpg' />
  <img src='Foo005.jpg' />
  <img src='Foo006.jpg' />
  <img src='Foo007.jpg' />
  <img src='Foo008.jpg' />
  <img src='Foo009.jpg' />
  <img src='Foo010.jpg' />
</root>