这是 HAML 中一个巨大且长期存在的问题。我已经通过两种不同的方式亲自解决了这个问题。
1)我将我想要的文本放在数组元素中,并使用一个
join(', ')
但这是一种非常糟糕的做事方式。
2) HAML 唯一的“解决方案”在于特殊的 > 字符。 > 字符删除输出 html 中的空格,因此在此标记输出之前或之后没有空格。
这是我能想到的最好的方法,我晚上睡不着觉,因为它太丑了。
%a{:href => 'here'} Github
%span> ,
%a{:href => 'there'} Twitter
关于最后一种技术的说明。
一个。如果你不使用   ;即使您的源代码中有空间,您也不会获得空间。使用引号 ( %span> #{", "}) 和空格不起作用,因为显然 HAML 会修剪输出。
b.您必须使用标签,因为据我所知,使用 > 只能在标签之后使用。不幸的是,使用 => 将不起作用。这将是我推荐的方法,但无论如何它都不能解决最后一个空间丢失的问题。
3) 在我的 rails 项目中,我使用了以下部分和助手的组合:
部分:_haml_comma.html.haml
%span> ,
helper.rb
def comma
render :partial => "shared/haml_comma"
end
.haml 文件:
%a{:href => 'here'} Github
= comma
%a{:href => 'there'} Twitter
4) 当你有一个 ENUMERABLE 并且正在 LOOPING 时,下面的 helper 和 partial 可能会对你有所帮助
application_helper.rb
# puts a comma after an element in a loop EXCEPT the last loop
def comma_separate(i:, total:, &block)
render layout: 'shared/comma_separate', locals: {i:i, total: total} do
capture(&block) if block
end
end
views/shared/_comma_separate.html.haml:
= succeed i + 1 < total ? ', ' : nil do
%span.some_class<
= yield
在您看来:
- enumerable.each_with_index do |w, i|
= comma_separate i: i, total: enumerable.size do
%b
= w
(此编辑是在 2019 年进行的,距离第一次发表评论整整 5 年。为什么这没有解决 HAML 维护者的问题?)