activeadmin / arbre

An Object Oriented DOM Tree in Ruby

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Using Arbre in ERB, how to access the ERB context?

chengguangnan opened this issue · comments

# show.html.erb

@username = 333

html = Arbre::Context.new do
  h2 "hello #{@username.to_s}"
end

concat html.to_s

It outputs

   hello 

Clearly the value @username defined outside is not accessible. How to fix that?

the quick answer is, you pass a hash in to the constructor of the context;

html = Arbre::Context.new({username: 333}) do
  h2 "hello #{username}"
end

html.to_s #=> "<h2>hello 333</h2>"

you can also pass in a helpers object to provide another context for method calling

check out the source, it is well documented in-line

commented

It also apparently doesn't get the route helpers in a rails erb template :(

Was going to use it in a project. Can't now :(


<%=
template = Arbre::Context.new(album: @album) do
  h3 "Songs for the #{link_to album.star.name, musician_path(album.star)} album: #{album.name}"
end

template.to_s
%>

will get you

undefined method `musician_path' for :Arbre::Context`

@williscool if you put the template in its own foo.html.arb file, it'll automatically get the Rails helpers.
Take a look at: https://github.com/gregbell/arbre/blob/master/lib/arbre/rails/template_handler.rb

commented

@daxter Aww shucks

Well I ended up going with erector because it has a generator that will convert your old html for you

http://erector.rubyforge.org/rails.html#tool

Which was mindblowingly awesome.

Arbre's syntax is way better in my opinion though. If it had a generator that would be really cool