html - 我如何缩小 ruby​​ on rails 中的 HTML 输出?

标签 html ruby-on-rails optimization haml minify

我有一个 ruby​​ on rails 应用程序,我正在使用 HAML 来构建 HTML 结构,

我想缩小/丑化输出“html”,删除不必要的空格和新行。

像这样:

<div class='wrapper v2-header-wrapper' id='fix-content'><div class='header header-search' style='text-align: center !important;'><nav class='navbar navbar-toggleable-md navbar-light bg-faded navbar-expand-lg'><button class='navbar-toggler navbar-toggler-right' onclick='openNav()' type='button'><span class='navbar-toggler-icon'><i class='fa fa-bars'></i></span></button><a class='navbar-brand mobile pull-left' href='/'><i class='fa fa-search'></i>

取而代之的是:

<div class='wrapper v2-header-wrapper' id='fix-content'>
<div class='header header-search' style='text-align: center !important;'>
<nav class='navbar navbar-toggleable-md navbar-light bg-faded navbar-expand- 
lg'>
<button class='navbar-toggler navbar-toggler-right' onclick='openNav()' 
type='button'>
<span class='navbar-toggler-icon'>
<i class='fa fa-bars'></i>
</span>
</button>
<a class='navbar-brand mobile pull-left' href='/'>
<i class='fa fa-search'></i>

非常感谢您的帮助,提前致谢。

最佳答案

试一试:

app/middleware/html_minifier.rb

class HtmlMinifier
  def initialize(app)
    @app = app
  end

  def call(env)

    # Call the underlying application, return a standard Rack response
    status, headers, response = @app.call(env)

    # Make sure we don't process CSS or JavaScript
    if headers["Content-Type"] =~ /text\/html/
      response.each do |chunk|
        [
          # Join lines
          [/[\r\n]+/, ""],

          # Remove whitespace between tags
          [/>\s+</, "><"],

          # Remove comments
          [/<!--(.|\s)*?-->/, ""],

          # Remove whitespace in inline JavaScript
          [/;\s+/, ";"],
          [/{\s+/, "{"]
        ].each do |regex, substitute|
          chunk.gsub! regex, substitute
        end
      end
    end

    # Return the new Rack response
    [status, headers, response]
  end
end

关于html - 我如何缩小 ruby​​ on rails 中的 HTML 输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52993937/

相关文章:

javascript - AngularJs ng-repeat 尚未渲染数据 http 200 响应

ruby-on-rails - Ruby on Rails if 语句不起作用,尽管变量具有 bool 值

python - 余弦相似度优化实现

javascript - 网站没有完全滚动到顶部

html - 使用 Flexbox 构建网格 - 如何设置多个元素/Div 并排放置?

html - 如何在 Angular 中的选择之外获取所选选项的索引?

ruby-on-rails - rake 数据库 :migrate fails

mysql - 在 ruby​​ on Rails 应用程序中禁用 SSL 模式

list - 如何避免不必要的计算?

java - 损坏发生后会发生去优化吗?