简体   繁体   English

Rails 5标签助手,变量中带有标签名称

[英]Rails 5 tag helper with tag name in variable

I am converting some older code which uses content_tag like this: 我正在转换一些使用content_tag旧代码,如下所示:

wrap_tag = 'p'
....
content_tag(wrap_tag, class: 'etc') do
  'some content'
end

which generates the expected 产生预期

<p class="etc">
Some content
</div>

I'd now like to update to use the tag syntax, but I am having troubles with this: 我现在想更新以使用tag语法,但是我遇到了麻烦:

wrap_tag = 'p'
...
tag wrap_tag, class: 'etc' do
  'some content'
end

Trying: tag.wrap_tag gives "<wrap-tag>some content</wrap-tag>" 尝试: tag.wrap_tag给出"<wrap-tag>some content</wrap-tag>"

Not unexpected, except that the underscore has become a hyphen. 除了下划线已成为连字符以外,这并不意外。

Other variations: 其他变化:

  • Using tag.p directly: <p>some content</p> 直接使用tag.p<p>some content</p>
  • Using tag.wrap_tag : <wrap-tag>some content</wrap-tag> 使用tag.wrap_tag<wrap-tag>some content</wrap-tag>
  • Using tag.wrap_tag.to_sym : <wrap-tag></wrap-tag> 使用tag.wrap_tag.to_sym<wrap-tag></wrap-tag>
  • Using tag wrap_tag : <p /> 使用tag wrap_tag<p />
  • Using tag wrap_tag.to_sym : <p /> 使用tag wrap_tag.to_sym<p />

Note: all the examples above included the do..content..end block shown initially . 注意:以上所有示例均包含最初显示的do..content..end

Is there a way to have the tag name in a variable and include content? 有没有办法在变量中包含标签名称并包含内容?

Thanks 谢谢


Trying the suggestion from jvillian to use send I find that 尝试使用jvillian的建议使用send我发现

wrap_tag = 'p'
content = 'some text'
helper.tag.send(wrap_tag, content)

returns "some text", and generally returns the second and subsequent arguments. 返回“一些文本”,并且通常返回第二个和后续参数。


It does seem, looking at actionview/helpers/tag_helper.rb, that the content_tag method checks for block_given? 看一下actionview / helpers / tag_helper.rb, content_tag方法似乎检查了block_given吗? and tag doesn't. 标签没有。

But whyyyyyyyyy (not) I will have to read through the PR again to find out. 但是,为什么(我)(我)将不得不再次通读PR来找出答案。

I find that if I do: 我发现如果这样做:

@arg = :div
tag.send @arg, class: 'etc' do 
  'some content'
end

...then I get: ...然后我得到:

<div class="etc">some content</div>

Similarly, if I do: 同样,如果我这样做:

@arg = :section
tag.send @arg, class: 'etc' do 
  'some content'
end

...then I get: ...然后我得到:

<section class="etc">some content</section>

If, however, I do: 但是,如果我这样做:

@arg = :p
tag.send @arg, class: 'etc' do 
  'some content'
end

...then I get: ...然后我得到:

{:class=>"etc"}

Which, obviously, is not what one expects . 显然,这不是人们所期望的 And, seems straight-up peculiar, because: 而且,似乎是直截了当的,因为:

tag.p class: 'etc' do 
  'some content'
end

...gives: ...给出:

<p class="etc">some content</p>

...which is all sunshine and lolipops. ...所有的阳光和脂肪

Gremlins? 小妖精? One can only wonder. 一个人只能纳闷。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM