Rails - Add HTML attribute without setting a value

☆樱花仙子☆ 提交于 2019-12-22 07:40:46

问题


I'm trying to create an image_tag and specify a data- attribute that does not have any value set to it. I'm trying to add data-tooltip, for use with Foundation 5 tooltips. It seems that if any value is actually set to this, Foundation uses the same tooltip text every time and ignores the title attribute of that element (so every tooltip will say whatever the first one you hovered on was... which seems buggy in and of itself on Foundation's part also)

This is what I need to generate:

<img src="[whatever]" title="My Tooltip" data-tooltip />

This will not work for me:

<img src="[whatever]" title="My Tooltip" data-tooltip="[insert anything here]" />

I have tried a number of different combinations, and read documentation, but it seems no matter what I put as the value, it ends up generating it like data-tooltip="null", or true, or false, or any string I pass.

image_tag(my_image, class: 'has-tip', title: "My Title Here", data: { tooltip: true })

回答1:


Try to pass in empty string as follows:

image_tag(my_image, class: 'has-tip', title: "My Title Here", data: { tooltip: "" })



回答2:


In Rails 4.1.4 using above tip :"data-tooltip" => '' renders data-tooltip without value.




回答3:


For an attribute with no value like multiple <input multiple type="file">, you can override the attribute default name, by uppercasing and setting an empty string. For example input_html: { Multiple: '' } But this is a hack.




回答4:


In rails 5, I was trying to add itemscope attribute with no value in the following link tag scenario:

    <%= link_to example_path(@example) do %>
      <span>
        <%= @example.name %>
      </span>
    <% end %>

I needed the resulting html a tag to show the itemscope attribute without any value like so:

<a itemscope href="example/path">
    <span>
       some text
    </span>
</a>

Notice the itemscope has no ="" or itemscope="itemscope".

I tried solutions from SO and other places and the only thing that worked for me was adding the following to the link_to tag: " itemscope" => ''. Notice the space between the first double quote and the word itemscope.

This seems to generate the desired outcome and also validated as schema.org tag on google (that is what i used the tag for).



来源:https://stackoverflow.com/questions/20308537/rails-add-html-attribute-without-setting-a-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!