Using Rails Helpers with Haml :: Engine

I have a Rails application in which I present a block of Haml elements stored in a model attribute. It would be nice to use Rails view helpers in this Haml block. I am currently using Haml :: Engine # rendering in the view helper to display the contents of this model attribute. It works pretty well, 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 this?

Best ideas?

+7
source share
3 answers

The rendering method allows you to specify the context. Something like

 base = Class.new do include ActionView::Helpers::AssetTagHelper include ApplicationHelper end.new Haml::Engine.new(src).render(base) 

can work.

+14
source
Marcel walked in the right direction. But you need to get a valid area for the rendering engine from somewhere. What I did was called an assistant with a valid scope:

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

+3
source
 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 

This works for me. Based on this problem .

0
source

All Articles