使用多行 <% %> 的最佳方法是什么?标签或 <% %>标签有多行?

发布于 2024-09-01 19:25:59 字数 595 浏览 4 评论 0原文

抱歉,如果标题不足以理解我要问的内容。 我是 Rails 开发人员,我使用了多行 <% %> ;在我看来,但现在我意识到这不是最佳实践,所以我来到这里,向你们所有优秀的人致敬,ROR 的正确方法是什么?

例如,如果我需要类似以下的内容,

 <% user =User.all %>
 <% name= [] %>
 <% count = 0 %>
  <% for user in users %>
    <% name << user.name %>
    <% count+=1%>
  <% end %>

我可以按如下方式进行吗?

 <% user =User.all 
    name= [] 
    count = 0
    for user in users 
      name << user.name 
      count+=1
    end 
 %>

我知道从数组中收集元素的更好方法但上面只是示例。 但我的问题是,是否可能,如果可以,哪种方法是正确的?

Sorry if the title is not enough to understand what i am asking about.
I am rails developer and i used multiple lines of <% %> in my views but now i realized that it's not best practice so i came here and like to you all excellent guys what is the correct way in ROR?

For example if i required to something like following

 <% user =User.all %>
 <% name= [] %>
 <% count = 0 %>
  <% for user in users %>
    <% name << user.name %>
    <% count+=1%>
  <% end %>

Can i do it as follows ?

 <% user =User.all 
    name= [] 
    count = 0
    for user in users 
      name << user.name 
      count+=1
    end 
 %>

I know better way of collecting element from array But above is just example.
But my question is, is it possible and if yes which is the correct way?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

∞觅青森が 2024-09-08 19:25:59

我认为正确的方法是完全不同的:将逻辑移出视图。

这篇博文解释了我的意思。

I think the correct way is something totally different: move logic out of views.

This blog post explains what I mean.

迷你仙 2024-09-08 19:25:59

在开始和结束处必须有 '<%' 或 '%>'
喜欢:

<% users = User.all 
    name= [] 
    count = 0
    for user in users 
      count+=1
    end %>

in start and end must has '<%' or '%>'
Like:

<% users = User.all 
    name= [] 
    count = 0
    for user in users 
      count+=1
    end %>
赠意 2024-09-08 19:25:59

每个代码块仅使用一对标签当然是更可取的,因为它会使输出更小。

代码实际上应该看起来像

<% names = User.all.map(&:name) %>

注意“count”可以通过names.size获得。

如果您需要混合 <% 和 <%= 您需要切换:

<% for user in User.all %>
<%= user.name %></br>
<% end %>

Using just a single pair of tags per code block is certainly preferable if only because it makes the output smaller.

The code should really rather look like

<% names = User.all.map(&:name) %>

Note that "count" can be obtained via names.size.

If you need to mix <% and <%= you need to switch:

<% for user in User.all %>
<%= user.name %></br>
<% end %>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文