代码之家  ›  专栏  ›  技术社区  ›  yegor256

如何使用Haml 6.3中的Haml::Engine渲染HTML?

  •  1
  • yegor256  · 技术社区  · 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.3渲染HAML模板的正确方法是什么?

    1 回复  |  直到 3 月前
        1
  •  1
  •   Progromatic World    3 月前

    在Haml 6.3中,由于库及其依赖关系的更新,渲染模板的语法略有变化。以下是使用HAML 6.3渲染HAML模板的正确方法:

    Haml 6.3的正确代码

    ruby代码

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

    变更说明:

    使用Haml::Template:初始化

    在Haml 6.3中,您应该使用Haml::Template.new来定义您的模板。 将HAML内容作为块传递给HAML::Template.new。

    渲染方法:

    在引擎实例上使用render方法,将上下文对象(例如object.new)和任何变量(例如bar)作为哈希传递。

    为什么会发生错误

    您遇到的错误是因为旧的Haml::Engine语法不再与Haml 6.3直接兼容。Haml现在在内部使用的Temple库对选项进行了更严格的验证,而且旧的初始化方法与新的API冲突。

    使用新语法可以解决这些问题,并将代码与更新的Haml库对齐。