【问题标题】:How do I find the path of a template file using ERB?如何使用 ERB 找到模板文件的路径?
【发布时间】:2012-09-05 23:04:01
【问题描述】:

我正在使用嵌入式 ruby​​ (ERB) 来生成文本文件。我需要知道模板文件的目录才能找到相对于模板文件路径的另一个文件。 ERB 中是否有一个简单的方法可以为我提供当前模板文件的文件名和目录?

我正在寻找类似于 __FILE__ 的东西,但提供的是模板文件而不是 (erb)。

【问题讨论】:

    标签: ruby erb


    【解决方案1】:

    当您使用 Ruby 中的 ERB api 时,您向 ERB.new 提供了一个字符串,因此 ERB 无法知道该文件的来源。但是,您可以使用 filename 属性告诉对象它来自哪个文件:

    t = ERB.new(File.read('my_template.erb')
    t.filename = 'my_template.erb'
    

    现在您可以在my_template.erb 中使用__FILE__,它将引用文件名。 (这就是 erb 可执行文件的作用,这就是为什么 __FILE__ 在您从命令行运行的 ERB 文件中起作用的原因。

    为了让它更有用一点,你可以用一个从文件中读取的新方法来修补 ERB 并设置filename

    require 'erb'
    
    class ERB
      # these args are the args for ERB.new, which we pass through
      # after reading the file into a string
      def self.from_file(file, safe_level=nil, trim_mode=nil, eoutvar='_erbout')
        t = new(File.read(file), safe_level, trim_mode, eoutvar)
        t.filename = file
        t
      end
    end
    

    您现在可以使用此方法读取 ERB 文件,__FILE__ 应该可以在其中工作,并参考实际文件而不仅仅是 (erb)

    t = ERB.from_file 'my_template.erb'
    puts t.result
    

    【讨论】:

    • 我也很想知道如何用 erubis 做到这一点
    • nvm,erubis也是一样。只需设置.filename = 'my_template.erb'
    猜你喜欢
    • 2013-01-27
    • 1970-01-01
    • 2017-12-07
    • 2016-06-18
    • 2017-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多