2

一連の変数がリストされた .erb ファイルを作成しました。

 <body>
    <h1>
        <%= header %>
    </h1>
    <p>
        <%= intro1 %>
    </p>
    <p>
        <%= content1 %>
    </p>
    <p>
        <%= content2 %>
    </p>
    <p>
        <%= content3 %>
    </p>
  </body>

次に、変数を含むテキスト ファイルがあります。

header=This is the header
intro1=This is the text for intro 1
content1=This is the content for content 1
content2=This is the content for content 2
content3=This is the content for content 3

テキスト ファイルから変数を取得し、.erb テンプレートに挿入する必要があります。これを行う適切な方法は何ですか?Railsサイト全体ではなく、Rubyスクリプトだけを考えています。小さなページのみですが、複数回実行する必要があります。

ありがとう

4

3 に答える 3

3

txtファイルをスキップし、代わりにymlファイルを使用します。

方法の詳細については、このサイトをチェックしてください:http: //innovativethought.net/2009/01/02/making-configuration-files-with-yaml-revised/

于 2012-05-02T22:30:52.267 に答える
3

多くの人が「保存されている場所から値を取得するにはどうすればよいか」からこれにたどり着いたと思います。<%= intro1 %>質問の残りの半分を無視しました:「メモリ内にあるRuby変数に置き換えるにはどうすればよいですか?

このようなものが動作するはずです:

require 'erb'
original_contents = File.read(path_to_erb_file)
template = ERB.new(original_contents)

intro1 = "Hello World"
rendered_text = template.result(binding)

ここでのbindingことは、ERB がレンダリングされるときに、すべてのローカル変数が内部で見えることを意味します。(技術的には、変数だけでなく、スコープで使用できるメソッドやその他のものもあります)。

于 2012-05-03T02:54:01.477 に答える
0

YMLについては同意します。本当にテキストファイルを使用したい (または持っている) 場合は、次のようなことができます:

class MyClass
  def init_variables(text)
    text.scan(/(.*)=(.*)\n/).each do |couple|
      instance_variable_set("@" + couple[0], couple[1])
    end
  end
end

my_obj = MyClass.new
my_obj.init_variables("header=foo\ncontent1=bar")
于 2012-05-02T23:04:22.563 に答える