Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to render HTML with Haml::Engine from Haml 6.3?

This code worked for Haml 5:

require 'haml/engine'
engine = Haml::Engine.new('= bar')
engine.render(Object.new, { bar: 'hello, world!' })

It doesn’t work with Haml 6.3:

/Users/yb/.rvm/gems/ruby-3.3.5/gems/temple-0.10.3/lib/temple/map.rb:88:in `validate_map!': undefined method `to_hash' for an instance of String (NoMethodError)

      map.to_hash.keys.each {|key| validate_key!(key) }
         ^^^^^^^^
Did you mean?  to_s
    from /Users/yb/.rvm/gems/ruby-3.3.5/gems/temple-0.10.3/lib/temple/mixins/options.rb:82:in `initialize'
    from /Users/yb/.rvm/gems/ruby-3.3.5/gems/temple-0.10.3/lib/temple/engine.rb:46:in `initialize'
    from a.rb:2:in `new'
    from a.rb:2:in `<main>'

What is the right way to render HAML template with Haml 6.3?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In Haml 6.3, the syntax for rendering templates has slightly changed due to updates in the library and its dependencies. Here’s the correct way to render a HAML template with Haml 6.3:

Correct Code for Haml 6.3

ruby code

require 'haml'

template = '= bar'
engine = Haml::Template.new { template }
output = engine.render(Object.new, bar: 'hello, world!')
puts output

Explanation of Changes:

Initialization with Haml::Template:

In Haml 6.3, you should use Haml::Template.new to define your template.
Pass the HAML content as a block to Haml::Template.new.

Render Method:

Use the render method on the engine instance, passing in the context object (e.g., Object.new) and any variables (e.g., bar) as a hash.

Why the Error Happened

The error you encountered is because the older Haml::Engine syntax is no longer directly compatible with Haml 6.3. The Temple library, which Haml now uses internally, has stricter validation for options, and the older initialization methods conflict with the new API.

Using the new syntax resolves these issues and aligns your code with the updated Haml library.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading