将HAML添加到Rails资产管道

Zam*_*nji 13 haml ruby-on-rails-3 ruby-on-rails-3.1 asset-pipeline

我想提供已通过HAML预处理的客户端模板.我尝试使用haml_assets gem并将以下代码添加到初始化程序:

Rails.application.assets.register_engine ".haml", Tilt::HamlTemplate
Run Code Online (Sandbox Code Playgroud)

当我访问资产时,这两种方法都提供原始HAML而不是编译HAML.如何将HAML添加到管道中?

Sam*_*ler 12

只是为了清理,因为我发现当前的答案有点恼人(导致我朝着正确的方向)

它工作,如果我在初始化文件中有这一行:

# config/initializers/haml_assets.rb
Rails.application.assets.register_engine '.haml', Tilt::HamlTemplate
Run Code Online (Sandbox Code Playgroud)

将haml文件放入assets文件夹,例如:

# app/assets/templates   
Run Code Online (Sandbox Code Playgroud)

千万不能使用haml_asset宝石,但!


小智 10

application.rb中的以下代码适用于Rails 3.2(在预编译后的开发和生产中):

require 'haml'

config.assets.paths << Rails.root.join("app", "assets", "templates")

class HamlTemplate < Tilt::HamlTemplate
  def prepare
    @options = @options.merge :format => :html5
    super
  end
end

config.before_initialize do |app|
  require 'sprockets'
  Sprockets::Engines #force autoloading
  Sprockets.register_engine '.haml', HamlTemplate
end
Run Code Online (Sandbox Code Playgroud)

这允许您将模板放在以后缀.html.haml命名的app/assets/templates中(您需要.html或其他.htm文件在预编译过程中生成而不是.html).


vau*_*han 5

这对我有用:

# app/assets/javascripts/test.html.haml

%p hello

# config/initializers/haml_template.rb

Rails.application.assets.register_mime_type 'text/html', '.html'
Rails.application.assets.register_engine '.haml', Tilt::HamlTemplate
Run Code Online (Sandbox Code Playgroud)

这适用于http://127.0.0.1:3000/assets/test.html.haml

Rails.application.assets是一个Sprockets::Environment.

请参阅此处以获取API参考:


Nil*_*lor 0

使用与我相同的方法:

%tr
  %th
    %a.action.link.show
  %td
  %td
Run Code Online (Sandbox Code Playgroud)

作为纯 haml 返回。但

%tr
  %th
    %a.action.link.show
  %td cell 2
  %td cell 3
Run Code Online (Sandbox Code Playgroud)

被用作 html 块。所以我认为这与哈姆宝石有关。您可以使用如下命令强制进行 haml 转换:

%tr
  %th
    %a.action.link.show
  %td &nbsp
  %td &nbsp
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你...