gpt4 book ai didi

ruby-on-rails - rails : Unable to nest content_tag

转载 作者:行者123 更新时间:2023-12-04 07:28:51 26 4
gpt4 key购买 nike

我编写了一个 Rails 助手来创建一个嵌套的 HTML 列表。但是,这没有正确呈现。请问我做错了什么?

助手

content_tag :ul do
[1, 2].each do |x|
content_tag(:li, x)
content_tag :ul do
['a', 'b'].each do |y|
content_tag(:li, y)
content_tag :ul do
['i', 'ii'].each do |z|
content_tag(:li, z)
end
end
end
end
end
end

预期输出

<ul>
<li>1</li>
<ul>
<li>a</li>
<ul>
<li>i</li>
<li>ii</li>
</ul>
<li>b</li>
<ul>
<li>i</li>
<li>ii</li>
</ul>
<li>2</li>
<ul>
<li>a</li>
<ul>
<li>i</li>
<li>ii</li>
</ul>
<li>b</li>
<ul>
<li>i</li>
<li>ii</li>
</ul>
</ul>
</ul>

实际输出

<ul></ul>

最佳答案

这是解决方案:

content_tag(:ul) do
[1, 2].map do |x|
content_tag(:li, x) <<
content_tag(:ul) do
['a', 'b'].map do |y|
content_tag(:li, y) <<
content_tag(:ul) do
['i', 'ii'].map do |z|
content_tag(:li, z)
end.join('').html_safe
end
end.join('').html_safe
end
end.join('').html_safe
end

问题是您必须在每个 content_tag block 的末尾返回一个 HTML 安全字符串:

# returns <li>asd</li>
content_tag('li') { 'asd' }

# returns <ul><li>asd</li></ul>
content_tag('ul') { content_tag('li') { 'asd' } }

# returns [1, 2]
[1, 2].each{ |x| content_tag('li', x) }

# returns ["<li>1</li>", "<li>2</li>"]
[1, 2].map{ |x| content_tag('li', x) }

# returns "<li>1</li><li>2</li>" not marked as HTML safe,
# because `join` generates a new string
[1, 2].map{ |x| content_tag('li', x) }.join('')

# returns "<li>1</li><li>2</li>" marked as HTML safe
[1, 2].map{ |x| content_tag('li', x) }.join('').html_safe

# returns "<ul><li>1</li><li>2</li></ul>"
content_tag('ul') do
[1, 2].map{ |x| content_tag('li', x) }.join('').html_safe
end

# returns "<ul><li>1</li><li>2</li></ul>"
content_tag('ul') do
content_tag('li') { 'asd' } # this is ignored, since it is not returned
[1, 2].map{ |x| content_tag('li', x) }.join('').html_safe
end

# returns "<ul><li>asd</li><li>1</li><li>2</li></ul>"
content_tag('ul') do
content_tag('li') { 'asd' } <<
[1, 2].map{ |x| content_tag('li', x) }.join('').html_safe
end

关于ruby-on-rails - rails : Unable to nest content_tag,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14992000/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com