【问题标题】:How do I embed CoffeeScript in Haml outside of Ruby/Rails?如何在 Ruby/Rails 之外的 Haml 中嵌入 CoffeeScript?
【发布时间】:2011-07-07 15:58:42
【问题描述】:

在 Rails 中使用 coffee-haml-filter 很容易。在 Rails 2 下,运行

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

在Rails 3下,可以添加一行

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

到您的 Gemfile 并执行 bundle install。 (这一切都假设您想使用 gerad 的 fork,它比 inem 的 original version 更新,在撰写本文时。)。

在任何其他 Ruby 应用程序中,这有点棘手,但仍然相当容易(例如,使用 Gemfile 和 Bundler.require;或者更简单的是直接从 gerad 的 repo 下载 coffee.rb 文件,将其粘贴在文件夹,然后require-ing)。

但是,如果我只是在命令行上使用haml 怎么办?有没有办法以 Haml 在系统范围内使用它的方式安装自定义过滤器?或者我是否可以使用 Haml 模板中的 require 语句来获取所需的过滤器?

【问题讨论】:

    标签: ruby haml coffeescript


    【解决方案1】:

    就在最近,一个新的 CoffeeScript Haml 过滤器问世了,它可以安装在系统级别,就像我想要的那样:https://github.com/paulnicholson/coffee-filter

    不过,您必须在命令行上使用参数 -r 'coffee-filter' 运行 Haml。见this discussion

    【讨论】:

      【解决方案2】:

      制作自定义 HAML 过滤器应该像在您的类中包含 Haml::Filters::Base 模块并覆盖渲染方法一样简单,但我无法使用 haml 脚本的 -r 选项使其工作,或者试图将过滤器代码直接放入 HAML 模板中。该脚本只是过早地失败了 Filter "coffee" is not defined 错误。

      所以我最终编写了自己的脚本。它没有使用您提到的 coffee-haml-filter,而是自己实现了 :coffee 过滤器。它将haml 脚本文件名作为参数。它肯定可以写得更好,但它对我的目的很有效。

      #! /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
      

      【讨论】:

      • 嗯...没有想到这种方法。谢谢。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-05
      • 1970-01-01
      • 1970-01-01
      • 2012-12-04
      • 2013-08-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多