【问题标题】:how to avoid using the same condition twice in slim views如何避免在苗条视图中两次使用相同的条件
【发布时间】:2018-08-27 06:51:58
【问题描述】:

我认为有以下代码:

.container
  .row
    .col
      h3 Header
      - if @status < 5
        p Text
    - if @status < 5
      .col
        p More text

正如你所见,由于压痕很小,我使用了两次相同的条件。有什么办法可以避免吗?

【问题讨论】:

  • 你想改变它只是为了“更好看”的目的还是还有一些性能问题?
  • 这种情况很常见,还不错。这里最令人担忧的是魔术数字5,它至少应该是:@status &lt; SOME_CONSTANT

标签: ruby-on-rails slim-lang


【解决方案1】:

我认为你唯一能做的就是重构它。

在任何地方都使用帮助程序而不是硬编码条件,这样当您决定将 5 更改为 6 时,您只需在一个地方进行更改。

辅助方法

def valid_status?(status)
  status < 5
end

查看(苗条)

.container
  .row
    .col
      h3 Header
      - if valid_status?(@status)
        p Text
    - if valid_status?(@status)
      .col
        p More text

或者至少给一个变量赋值一次

- valid_status = @status < 5
.container
  .row
    .col
      h3 Header
      - if valid_status
        p Text
    - if valid_status
      .col
        p More text

【讨论】:

  • 它或多或少与问题相同。 :)
  • 无论如何你不能改变html结构,所以它必须是一样的
  • 唯一的变化是您使用条件的方式。在这种情况下,通过使用辅助方法,您可以避免必须在 2-3 处更改条件的问题
【解决方案2】:

您需要将条件提取到像 Deepak 建议的助手中,并使用 partial render 提取 html sn-p。或多或少是这样的:

.container
  .row
    .col
      h3 Header
        = render "render_text_1" if status_5? # Humanize status code to be more clear
    .col
      = render "render_text_2" if status_5?

【讨论】:

    【解决方案3】:

    似乎这个标记没有什么问题,所以最好的解决方案是保持原样。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-24
      • 2020-03-12
      • 2015-04-27
      • 1970-01-01
      • 1970-01-01
      • 2017-12-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多