Ruby-on-rails 在没有 <%= 的情况下在 ERB 中打印?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1737252/
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:58:05  来源:igfitidea点击:

Print in ERB without <%=?

ruby-on-railserb

提问by Cheng

Sometimes it's more convenient to print in <%%>. How to do it in Rails?

有时用<%%> 打印更方便。如何在 Rails 中做到这一点?

回答by Omar Qureshi

http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-concat

http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-concat

Should be what you are looking for.

应该是你要找的。

E.g. the following statement using concat:

例如以下语句使用concat

<% concat "Output" %>

is equivalent to:

相当于:

<%= "Output" %>

回答by Evolve

In ERB: The <% %> signify that there is Ruby code here to be interpreted. The <%= %> says output the ruby code, ie display/print the result.

在 ERB 中: <% %> 表示这里有 Ruby 代码需要解释。<%= %> 表示输出 ruby​​ 代码,即显示/打印结果。

So it seems you need to use the extra = sign if you want to output in a standard ERB file.

因此,如果要在标准 ERB 文件中输出,似乎需要使用额外的 = 符号。

Otherwise, you could look at alternatives to ERB which require less syntax,.. maybe try something like HAML. http://haml-lang.com/tutorial.html

否则,您可以查看需要较少语法的 ERB 替代方案,.. 可以尝试使用 HAML 之类的方法。http://haml-lang.com/tutorial.html

Example:

# ERB
<strong><%= item.title %></strong>

# HAML
%strong= item.title

Is that more convenient?

这样更方便吗?

回答by brianegge

erbhas two method to evaluate inline ruby expressions. The <%which evaluates the expression and the <%=which evaluates and prints. There is no global object to print to within the binding context.

erb有两种方法来评估内联 ruby​​ 表达式。在<%该计算表达式和<%=其评估和打印。在绑定上下文中没有要打印到的全局对象。

As mentioned by Omar, there is a concatmethod, which is part of ActionView. This will do what you want.

正如 Omar 所提到的,有一个concat方法,它是 ActionView 的一部分。这会做你想做的。

Unlike a scripting language escape, there is no default output for erb. Since erb is simply a function, and given a template and binding will return a variable, it returns the values of text and functions recursively.

与脚本语言转义不同,erb 没有默认输出。由于 erb 只是一个函数,并且给定模板和绑定将返回一个变量,因此它递归地返回文本和函数的值。

There is hot debate as to how much logic should be allowed in a view, but as little as possibleis what most people aim for. If you are putting more code than text in the view, you may want to consider refactoring your code.

关于视图中应该允许多少逻辑存在激烈争论,但尽可能少是大多数人的目标。如果您在视图中放置的代码多于文本,您可能需要考虑重构您的代码。