Reputation: 3724
I've got a HAML partial that receives a variable bar
, and I'd like to inject that variable in the link_to path.
For example:
= link_to new_foo_path, class: 'source card' do
.stuff
I want to replace foo with bar.
I've tried:
= link_to new_#{bar}_path, class: 'source card' do
and a dozen other things, but nothing seems to work.
Thoughts?
Upvotes: 9
Views: 4783
Reputation: 2616
I encountered a similar situation so I created a view helper. For your case I guess you can do something similar.
Create a view helper function inside helpers/application_helper.rb
:
def custom_path pathvar
if pathvar == 'foo'
new_foo_path
elsif pathvar == 'bar'
new_bar_path
end
end
Then in your view, you can use it like this:
= link_to custom_path(bar), class: 'source card' do
You can modify the example as per your needs. This looks more elegant to me.
Upvotes: 1
Reputation: 10406
You can add parameters to the link helper like this:
link_to "New Foo", new_foo_path(bar: "bar")
Upvotes: 1
Reputation: 2136
You can try it like this:
link_to send("new_#{bar}_path"), class: "source card" do
Basically, send makes something a method or variable, and it allows you to combine everything in that string into one variable.
Upvotes: 14
Reputation: 18670
I think you can use eval
:
= link_to eval("new_#{bar}_path"), class: 'source card' do
Upvotes: 1