erb templates access to variables

381 views
Skip to first unread message

tcurdt

unread,
Aug 8, 2012, 5:31:57 AM8/8/12
to babush...@googlegroups.com
I cannot convince the erb template to get access to the (local) variable. Tried the following

dep 'test', :other, :items do
  ...
  meet {
      (items.current_value||[]).each do |item_name|
      render_erb 'items/template.erb', :to => item_path(item_name)
    end
    (items.current_value||[]).each do |item_name|
      render_erb 'items/template.erb', :to => item_path(item_name), :context => { 'item_name' => item_name }
    end
  }

with a simple template referring to <%= item_name %>

Just gives me a undefined local variable or method 'item_name' for #<Babushka::DepContext:0xa000bb8>

Don't get it. At least the second one should work. Any idea?

cheers,
Torsten

tcurdt

unread,
Aug 12, 2012, 2:42:18 PM8/12/12
to babush...@googlegroups.com
Ping.

Anyone? Ben?

Ben Hoskings

unread,
Aug 12, 2012, 8:12:58 PM8/12/12
to babush...@googlegroups.com
Sorry about the delay, this one got lost in my inbox.

It's not possible to pass local variables to the templates, this isn't something that ruby supports. ERb templates are rendered against a binding, i.e. in the context of some ruby object:

ERB.new(template_text).result(binding)

The template is rendered with the dep as its binding, so anything defined on the dep itself will be available in the template. So you have to make `item_name` available on the dep as a method (or an ivar, or any other way you'd access it locally). A local variable doesn't work because it's not actually defined on the object's binding, it's just in local scope (in your case, as a block argument).

Perhaps the dep could be rewritten to render a single template, which means item_name would become a dep parameter (which is available to the template, because it's really a method).

(Rails jumps through hoops to allow values to be passed in via the :locals option. Each value that's passed is defined on-the-fly as a method on whatever object the template is evaluated against.)

The 'context' option is for specifying a custom binding, i.e. the thing that will be instance eval'ed against. It's intended as an internal option; it's the dep itself that is the binding by default. If you pass another object, you won't have access to any of the dep's methods in the template anymore.

- Ben
> --
> To post, email babush...@googlegroups.com
> To unsubscribe, email babushka_app...@googlegroups.com
> ~
> http://babushka.me
> http://github.com/benhoskings/babushka
> http://groups.google.com/group/babushka_app

Reply all
Reply to author
Forward
0 new messages