简体   繁体   English

Ruby on Rails:在link_to辅助路径中使用Variable

[英]Ruby on Rails: Use Variable in link_to helper path

I've got a HAML partial that receives a variable bar , and I'd like to inject that variable in the link_to path. 我有一个接收变量bar的HAML部分,我想在link_to路径中注入该变量。

For example: 例如:

= link_to new_foo_path, class: 'source card' do
    .stuff

I want to replace foo with bar. 我想用bar替换foo。

I've tried: 我试过了:

= link_to new_#{bar}_path, class: 'source card' do

and a dozen other things, but nothing seems to work. 还有其他十几件事,但似乎没什么用。

Thoughts? 思考?

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. 基本上,send使某些方法或变量成为可能,并且它允许您将该字符串中的所有内容组合成一个变量。

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 : 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. 这对我来说看起来更优雅。

您可以像这样向链接助手添加参数:

link_to "New Foo", new_foo_path(bar: "bar")

我想你可以使用eval

= link_to eval("new_#{bar}_path"), class: 'source card' do

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM