How to embed CoffeeScript in Haml outside of Ruby / Rails?

Easy to use coffee-haml-filter in Rails. In the Rails 2 section, run

script/plugin install git://github.com/gerad/coffee-haml-filter.git 

In the Rails 3 section you can add a line

 gem 'coffee-haml-filter', :git => 'git://github.com/gerad/coffee-haml-filter.git' 

into your Gemfile and run bundle install . (It's all assumed that you want to use the gerad plug, which is more modern than the inem original version , starting with this entry.).

In any other Ruby application, this is a little more complicated, but still quite easy to do it (for example, using Gemfile and Bundler.require ), or, more simply, by loading the coffee.rb file directly from gerad repo, pasting it into the folder and require -ing).

But what if I just use haml on the command line, for example? Is there a way to set a custom filter so that Haml uses it in a system-wide? Or could I possibly use the require statement from the Haml template to get the filter you need?

+4
source share
2 answers

More recently, a new CoffeeScript Haml filter has appeared, which can be installed at the system level, as you would like: https://github.com/paulnicholson/coffee-filter

However, you must run Haml with the -r 'coffee-filter' arguments on the command line. See this discussion .

+4
source

Creating a custom HAML filter should be as simple as including the Haml::Filters::Base module in your class and overriding the rendering method, but I could not get it to work with the -r haml script option, or trying to directly insert the filter filter into HAML template. The script error too early using the coffee filter is not defined.

So, I wrote my own script. It does not use the coffee-haml filter that you mentioned, but uses the :coffee filter itself. The argument name is the haml script file name. It would definitely be better written, but it works well for my purposes.

 #! /usr/bin/env ruby require 'tempfile' require 'haml' TEMPDIR = '/dev/shm' module Haml::Filters::Coffee include Haml::Filters::Base def render(text) tmpf = Tempfile.new('hamlcoffee', TEMPDIR) tmpf.write text tmpf.close output = `coffee -pl '#{tmpf.path}'` # strip the first and last line, # since the js code is wrapped as a function output = output.lines.collect[1..-2].join return output end end template = File.read(ARGV[0]) haml_engine = Haml::Engine.new(template) output = haml_engine.render puts output 
+4
source

Source: https://habr.com/ru/post/1342056/


All Articles