Empty attribute with Ruby HAML

大城市里の小女人 提交于 2019-11-27 12:40:06

问题


I'm implementing Schema microformats on a Ruby project using HAML and can't figure out how to set an empty attribute on a tag. I tried nil and false, but they simply do not shown.

Example: <div itemscope>

I'm tring to set an empty itemscope attribute.

Code added from comment by @StrangeElement:

My code:

.agency.premium{:itemscope => true, :itemtype => 'schema.org/ProfessionalService';} 

:itemscope => true seems to be the recommended approach from HAML's documentation. I get the same result as I would get with :itemscope => '', a XHTML-valid attribute with an empty value (i.e. <div itemscope="">).

Probably fine, but I'd rather have it empty as is documented in the Schema doc.


回答1:


Using something like

%div{:itemscope => true}

is the correct way to specify this in your Haml file.

How this is rendered depends on how you set Haml's format option. The default in Haml 3.1 is xhtml, and with that it will render as itemprop='itemprop', which is valid xhtml. To render with minimized attributes (like <div itemscope>) you need to set the format to html4 or html5. (In Rails 3 the default is html5, and in Haml 4.0 the default is html5).

How to set the Haml options depends on how you are using it, see the options section in the docs.

For example, using Haml directly in Ruby, this:

engine = Haml::Engine.new '%div{:itemscope => true}'
puts engine.render

produces the default xhtml with full attributes:

<div itemscope='itemscope'></div>

But this:

engine = Haml::Engine.new '%div{:itemscope => true}', :format => :html5
puts engine.render

produces the desired result with minimized attributes:

<div itemscope></div>



回答2:


If someone is interested in how to put more words in that way, he may use "foo bar" => true:

%option{ "disabled selected value" => true } Choose an option

results is:

<option disabled="" selected="" value="">Choose an option</option>

and works as expected.




回答3:


The accepted answer works, but it produces an HTML attribute with value.

If you want the attribute only to be output on HTML, without value, you can use the HTML-style attributes syntax of HAML:

%div(itemscope)


来源:https://stackoverflow.com/questions/6244052/empty-attribute-with-ruby-haml

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