カスタムフィルターでHamlを使用します
-
13-10-2019 - |
質問
私はHamlとCoffeescriptに非常に興奮しており、非レール環境でそれらを使用する方法を示すチュートリアルに取り組んでいます。したがって、Hamlには簡単に使用できるコマンドラインユーティリティがあります
haml input.haml output.html.
そして、素晴らしいことに、プロジェクトが存在します(多くのフォークの1つ: https://github.com/aussieek/coffee-haml-filter)CoffeeScriptをHamlファイル内のJSに変換するカスタムフィルターを提供することを目的としています。残念ながら(または何かが足りないのですか?)、Hamlはコマンドラインまたは構成ファイルでカスタムフィルターを指定することを許可していません。
私は(Rubyのファンでも、それを十分に知っているわけではありません)、このヘルパースクリプトでそれを解決することができました(どこかで賢い提案に基づいて):haml.rb
require 'rubygems'
require 'active_support/core_ext/object/blank'
require 'haml'
require 'haml/filters/coffee'
template = ARGV.length > 0 ? File.read(ARGV.shift) : STDIN.read
haml_engine = Haml::Engine.new(template)
file = ARGV.length > 0 ? File.open(ARGV.shift, 'w') : STDOUT
file.write(haml_engine.render)
file.close
最初の要求を除いて、これは非常に簡単です。
今、質問は次のとおりです。
1)本当に使用する必要がありますか、それともカスタムフィルターを使用してHTMLコンピレーションにオンデマンドHamlを使用する別の方法がありますか?
2)Haml Watchモードはどうですか?それは素晴らしくて便利です。もちろん、でポーリングスクリプトを作成できます python
これにより、ディレクトリが変更され、これを呼び出します .rb
スクリプトですが、汚い解決策のように見えます。
Heikkiによる返信に加えて, 、私の解決策は次のとおりです。https://gist.github.com/759002
便利だと思うなら、お気軽に使用してください
解決
1)はいと言います。 (コマンドラインのオプションでも運がありませんでした)
2)コーヒースクリプトフィルターを使用してこの例を取得しました。ファイル監視は行われます fssm gem. 。入力フォルダーでHamlファイルの変更を再帰的に追跡し、.htmlファイル拡張子を使用してフォルダーを出力するようにします。
watch.rb:
require 'rubygems'
require 'fssm'
require 'haml'
require 'coffee-haml-filter'
require 'active_support/core_ext/object/blank'
def render(input_dir, output_dir, relative)
input_path = File.join(input_dir, relative)
output_path = File.join(output_dir, relative).gsub(/\.haml$/, ".html")
haml_engine = Haml::Engine.new(File.read(input_path))
puts "Rendering #{input_path} -> #{output_path}"
FileUtils.makedirs(File.dirname(output_path))
File.open(output_path, 'w') do |file|
file.write(haml_engine.render)
end
end
input_dir = File.expand_path(ARGV.length > 0 ? ARGV.shift : '.')
output_dir = File.expand_path(ARGV.length > 0 ? ARGV.shift : input_dir)
puts "Input folder: '#{input_dir}'"
puts "Output folder: '#{output_dir}'"
FSSM.monitor(input_dir, '**/*.haml') do
create {|base, relative| render(input_dir, output_dir, relative) }
update {|base, relative| render(input_dir, output_dir, relative) }
delete {|base, relative|
output_path = File.join(output_dir, relative).gsub(/\.haml$/, ".html")
puts "Deleting #{output_path}"
File.delete(output_path)
}
end
使用法:
ruby watch.rb input_folder output_folder
他のヒント
良いニュース:レールから独立して動作するように設計された新しいcoffeescripthamlフィルターがあります!
https://github.com/paulnicholson/coffee-filter
Coffee-haml-filterよりも間違いなくお勧めします。
--require
/-r
オプションは、coffeescriptフィルターをロードするために機能する必要があります。最新のバージョンではありませんが、それはバグです。次のリリースで修正されます。