如何使用safe_concat创建多个content_tags?

时间:2014-10-14 13:54:56

标签: ruby-on-rails ruby-on-rails-4 string-concatenation content-tag

我尝试使用content_tag和safe_concat连接多个标签,例如:

content_tag(:select, multiple: "multiple", :name => "contact[resources]") do
    content_tag(:optgroup, label: "LABEL", id: "some-id") do 
      safe_concat(
        if condition1
          (content_tag(:option, value: "val1") { "Val1" } )
        end
        if condition2
          (content_tag(:option, value: "val2") { "Val2" } )
        end              
      )
    end                
  end

但我一直收到以下错误:

syntax error, unexpected keyword_if, expecting ')' 
syntax error, unexpected end-of-input, expecting keyword_end

1 个答案:

答案 0 :(得分:1)

你需要在safe_concat中包装每一个输出,比如

content_tag(:select, multiple: "multiple", :name => "contact[resources]") do
  content_tag(:optgroup, label: "LABEL", id: "some-id") do 
    if condition1
      safe_concat(content_tag(:option, value: "val1") { "Val1" } )
    end
    if condition2
      safe_concat(content_tag(:option, value: "val2") { "Val2" } )
    end              
  end                
end