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?
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.