Rails / Bootstrap / HAML - How to convert this code to display flash messages to HAML?

岁酱吖の 提交于 2020-01-15 06:54:17

问题


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.

The code:

<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

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.


回答1:


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:

view

%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


来源:https://stackoverflow.com/questions/31094771/rails-bootstrap-haml-how-to-convert-this-code-to-display-flash-messages-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!