Empty attribute with Ruby HAML

I am implementing schema microformats in a Ruby project using HAML and cannot figure out how to set an empty attribute in a tag. I tried nil and false, but they just don't show.

Example: <div itemscope>

I am trying to set an empty itemscope attribute.

Code added from @StrangeElement comment:

My code is:

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

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

Probably great, but I would prefer it to be empty as described in the Schema document.

+49
ruby ruby-on-rails haml
Jun 05 2018-11-11T00:
source share
3 answers

Using something like

 %div{:itemscope => true} 

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

How this works out depends on how you set the Haml format parameter. By default, Haml 3.1 has xhtml , and with that it will display as itemprop='itemprop' , which is a valid xhtml. For rendering with minimal attributes (e.g. <div itemscope> ) you need to set html4 or html5 format. (Rails 3 uses html5 by default, and Haml 4.0 uses html5 by default.)

How to set Haml parameters depends on how you use it, see the parameters section in the docs .

For example, using Haml directly in Ruby, this is:

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

creates xhtml by default with full attributes:

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

But this:

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

creates the desired result with minimized attributes:

 <div itemscope></div> 
+73
Jun 06 2018-11-11T00:
source share

If someone is interested in how to add more words this way, he can use "foo bar" => true :

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

result:

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

and works as expected.

0
Feb 06 '17 at 9:18
source share

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

If you want the attribute to be displayed only in HTML, without a value, you can use the HAML HTML style attribute syntax :

 %div(itemscope) 
0
Jun 27. '18 at 10:11
source share



All Articles