Ruby-on-rails 如何在动态链接中使用 HAML?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14052979/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 21:13:23  来源:igfitidea点击:

How do I use HAML in a dynamic link?

ruby-on-railsrubyruby-on-rails-3haml

提问by Arihant Godha

I am trying to create a link using HAML which looks like the this

我正在尝试使用 HAML 创建一个链接,看起来像这样

=link_to("Last updated on<%=@last_data.date_from.month %>",'/member/abc/def?month={Time.now.month}&range=xyz&year={Time.now.year}')

It is not taking the Ruby code and it is displaying that as a string

它没有采用 Ruby 代码,而是将其显示为字符串

Last updated on<%=@last_data.date_from.month %>

最后更新于<%=@last_data.date_from.month %>

and in the URL as well it is not taking the function Time.now.monthor Time.now.year.

并且在 URL 中它也没有采用函数Time.now.monthTime.now.year.

How do I pass Ruby code in URL and in the string ?

如何在 URL 和字符串中传递 Ruby 代码?

回答by Ji?í Pospí?il

You should probably use something like this:

你可能应该使用这样的东西:

= link_to("Last updated on #{@last_data.date_from.month}", "/member/abc/def?month=#{Time.now.month}&range=xyz&year=#{Time.now.year}")

Note that in the second string, it's necessary to change the 'to ". Also if the link text is getting long, you can use something like this:

请注意,在第二个字符串中,有必要将 更改'"。此外,如果链接文本变长,您可以使用以下内容:

= link_to("/member/abc/def?month=#{Time.now.month}&range=xyz&year=#{Time.now.year}") do
  Last updated on #{@last_data.date_from.month}

回答by Gosha Arinich

Everything after the =in HAML is a Ruby expression. Ruby doesn't interpolate strings the way HAML does, it has own way of such interpolation.

=in HAML之后的所有内容都是 Ruby 表达式。Ruby 不像 HAML 那样插入字符串,它有自己的这种插入方式。

In Ruby, when you want to have string value of some variable inside another string, you could do.

在 Ruby 中,当您想在另一个字符串中包含某个变量的字符串值时,您可以这样做。

"Some string #{Time.now}"

So, it should be:

所以,应该是:

= link_to "Last updated on #{@last_data.date_from.month}", "/member/abc/def?month=#{Time.now.month}&range=xyz&year=#{Time.now.year}"

回答by imechemi

A simple example with easy syntax:

一个简单的语法示例:

 link_to "Profile #{rubycode}", "profile_path(@profile)/#{ruby_code}", class: "active"