从 Rails Helper 返回多个标签的最佳方法是什么?
我想创建一个隐藏字段并在一个助手中创建一个链接,然后将两者输出到我的 erb。
<%= my_cool_helper "something", form %>
应该输出
link_to "something", a_path
form.hidden_field "something".tableize, :value => "something"
帮助器的定义是什么样子的结果? link_to 和 form.hidden_field 的细节并不重要。 重要的是,如何返回两个不同调用的输出。
I want to create a hidden field and create a link in one helper and then output both to my erb.
<%= my_cool_helper "something", form %>
Should out put the results of
link_to "something", a_path
form.hidden_field "something".tableize, :value => "something"
What would the definition of the helper look like? The details of what link_to and the form.hidden_field don't really matter. What matters is, how do I return the output from two different calls.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
做这件事有很多种方法。
请记住,现有的 Rails 助手(例如
link_to
等)仅输出字符串。 您可以将字符串连接在一起并返回(如果事情很简单,这就是我大多数时候所做的)。EG:
如果您正在做更复杂的事情,您可以将该代码放入部分代码中,然后让您的助手调用
render :partial
。如果您正在做比这更复杂的事情,那么您可能需要查看 errtheblog 的 block_to_partial 帮助器,这非常酷
There are several ways to do this.
Remember that the existing rails helpers like
link_to
, etc, just output strings. You can concatenate the strings together and return that (which is what I do most of the time, if things are simple).EG:
If you're doing things which are more complicated, you could just put that code in a partial, and have your helper call
render :partial
.If you're doing more complicated stuff than even that, then you may want to look at errtheblog's block_to_partial helper, which is pretty cool
到目前为止,我想出的最好的方法是:
有更好的方法吗?
So far the best I have come up with is:
Is there a better way?
使用
safe_join
。我通常更喜欢仅与
+
连接,如 Orion Edwards 的答案 所示,但这里还有另一个选择我最近发现。它的优点是明确列出所有元素以及这些元素的连接。
我发现对于长元素,
+
符号可能会在行尾丢失。 此外,如果您要连接多个元素,我发现将它们列在这样的数组中对于下一个读者来说会更明显。Using
safe_join
.I typically prefer just concatenating with
+
, as shown in Orion Edwards's Answer, but here's another option I recently discovered.It has the advantage of explicitly listing all of the elements and the joining of those elements.
I find that with long elements, the
+
symbol can get lost at the end of the line. Additionally, if you're concatenating more than a few elements, I find listing them in an Array like this to be more obvious to the next reader.只是在这里简化一些其他答案。
just simplifying some other answers in here.
这对我有用。
This worked for me.
如果您想缓冲除字符串之外的其他输出,则可以使用
concat
而不是+
。看到这个 - http://thepugautomatic.com/2013/06/helpers/
If you want to buffer other output which apart from string then you can use
concat
instead of+
.see this - http://thepugautomatic.com/2013/06/helpers/