8
votes

I have a Rails app in which I am rendering a block of Haml stuff stored in a model attribute. It would be nice to use Rails view helpers in that block of Haml. Currently I am using the Haml::Engine#render in a view helper to render the content of this model attribute. It works well enough but I can't use things like =link_to. To illustrate the problem:

irb(main):003:0> haml_text=<<"EOH"
irb(main):004:0" %p
irb(main):005:0"   =image_tag 'someimage'
irb(main):006:0" EOH
=> "%p\n  =image_tag 'someimage'\n"
irb(main):007:0> engine = Haml::Engine.new(haml_text)
=> #<Haml::Engine:0x7fa9ff7f1150 ... >
irb(main):008:0> engine.render
NoMethodError: undefined method `image_tag' for #<Object:0x7fa9ff7e9a40>
        from (haml):2:in `render'
        from /usr/lib/ruby/gems/1.8/gems/haml-3.0.25/lib/haml/engine.rb:178:in `render'
        from /usr/lib/ruby/gems/1.8/gems/haml-3.0.25/lib/haml/engine.rb:178:in `instance_eval'
        from /usr/lib/ruby/gems/1.8/gems/haml-3.0.25/lib/haml/engine.rb:178:in `render'
        from (irb):8

Any thoughts on how to do that?

Better ideas?

3

3 Answers

14
votes

The render method allows you to specify a context. Something like

base = Class.new do
  include ActionView::Helpers::AssetTagHelper
  include ApplicationHelper
end.new

Haml::Engine.new(src).render(base)

could work.

3
votes

Marcel was going in the right direction. But you need to get a valid scope for the render engine from somewhere. What I did was call the helper with a valid scope like this:

In my_view/edit.html.haml

=my_revertable_field(self, 'hello world')

In application_helper.rb

def my_revertable_field(haml_scope, title, field)
      template =<<EOS
.field
  #{label}
  = text_field_tag #{field.name}, #{field.amount}, :size=>5, :class=>"text"
  = image_tag("refreshArrow.gif",:class=>"revert-icon", :style=>"display:none;",:title=>"Revert to default, #{field.default}")
EOS
end

Then you have a valid haml scope and so image_tab, form_tag_helpers all work

1
votes
class RailsRenderingContext
  def self.create(controller)
    view_context = ApplicationController.helpers
    class << view_context; include Rails.application.routes.url_helpers; end

    view_context.request = controller.request
    view_context.view_paths = controller.view_paths
    view_context.controller = controller

    view_context
  end
end

class MyController < ApplicationController
  def show
    # ...
    engine = Haml::Engine.new haml
    ctx = RailsRenderingContext.create(self)
    engine.render ctx 
  end
end

It works for me. Based on this issue.