Rails/Bootstrap/HAML-如何转换此代码以将Flash消息显示为HAML? [英] Rails / Bootstrap / HAML - How to convert this code to display flash messages to HAML?

查看:116
本文介绍了Rails/Bootstrap/HAML-如何转换此代码以将Flash消息显示为HAML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将以下代码转换为HAML,以在Rails 4.2.2应用程序中处理Bootstrap的警报消息.我已经使用html2haml和在线转换器进行了手动尝试,但是我得到的代码永远无法正常工作.

I want to convert the following code to HAML to handle Bootstrap's alert messages in a Rails 4.2.2 application. I've tried manually, using html2haml and online converters and the code I get never works.

代码:

<div class="alert 
    <%= 
    case type.to_sym 
    when :alert, :danger, :error, :validation_errors
        'alert-danger'
    when :warning, :todo
        'alert-warning'
    when :notice, :success
        'alert-success'
    else 
    'alert-info'
    end
    %>
     alert-dismissible" role="alert">
    <button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
    <%= content %>
</div>

这是我从转化者那里得到的:

This is what I get from converters:

.alert.case.when.:validation_errors.when.:todo.when.:success.else.end.alert-dismissible{:class => "<haml_loud> type.to_sym :alert, :danger, :error, 'alert-danger' :warning, 'alert-warning' :notice, 'alert-success' 'alert-info' </haml_loud>", :role => "alert"}
  %button.close{"data-dismiss" => "alert", :type => "button"}
    %span{"aria-hidden" => "true"} ×
    %span.sr-only Close
  = content

我知道它很丑陋,但这是我发现的唯一可以与Bootstrap 3.5.5兼容的代码.如果有人对使用HAML的新代码有建议,我很乐意听.

I know it's ugly but it is the only code I have found that works out of the box with Bootstrap 3.5.5. If anyone has suggestions for new code using HAML, I'm open to hear.

推荐答案

如果要将多行Ruby代码放在HTML元素的属性中,HAML并不是很好.无论如何,这被认为是一种不好的做法,因为它会使您的视图复杂化,因此我将使用一个助手来简化视图.例如,您可以创建一个helpers/alert_helper.rb文件.

HAML isn't real great if you want to put multi-line Ruby code inside of an HTML element's attributes. That's considered sort of a bad practice anyway because it is complicating your view, so I would instead use a helper to simplify the view. For example, you could create a helpers/alert_helper.rb file.

helpers/alert_helper.rb

module AlertHelper
  def build_alert_classes(alert_type)
    classes = 'alert alert-dismissable '
    case alert_type.to_sym 
    when :alert, :danger, :error, :validation_errors
        classes += 'alert-danger'
    when :warning, :todo
        classes += 'alert-warning'
    when :notice, :success
        classes += 'alert-success'
    else 
        classes += 'alert-info'
    end
  end
end

然后在您看来,它将变成这样:

Then in your view, it would become this:

视图

%div{ class: build_alert_classes(type), role: "alert" }
  %button.close{ type: "button", "data-dismiss" => "alert" }
    %span{ "aria-hidden" => true } &times;
    %span.sr-only Close
  = content

这篇关于Rails/Bootstrap/HAML-如何转换此代码以将Flash消息显示为HAML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆