如何用Haml 6.3的Haml::Engine渲染HTML?兼容问题求解
Haml 6.3 模板渲染的正确方式
问题背景
以下代码在 Haml 5 中可正常运行:
require 'haml/engine' engine = Haml::Engine.new('= bar') engine.render(Object.new, { bar: 'hello, world!' })
但在 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>'
错误原因
Haml 6 重构了 Haml::Engine#render 的参数规则:
- Haml 5 中参数顺序为
render(上下文对象, 局部变量哈希) - Haml 6 中调整为
render(局部变量哈希, 上下文对象)(上下文对象为可选参数)
原代码将局部变量哈希放在第二个参数位置,会被 Haml 6 误认为是引擎配置选项,从而触发类型错误。
正确写法
写法1:仅传递局部变量(最常用)
不需要绑定特定上下文时,直接传入局部变量哈希即可:
require 'haml/engine' engine = Haml::Engine.new('= bar') engine.render({ bar: 'hello, world!' }) # 可省略哈希大括号 engine.render(bar: 'hello, world!')
写法2:指定上下文对象
需要绑定特定上下文对象时,将其放在第二个参数位置:
require 'haml/engine' engine = Haml::Engine.new('= bar') engine.render({ bar: 'hello, world!' }, Object.new) # 可省略哈希大括号 engine.render(bar: 'hello, world!', Object.new)
内容的提问来源于stack exchange,提问作者yegor256
相关产品推荐
相关产品推荐

