简体   繁体   English

从.txt文件将变量插入ERB

[英]Inserting variables into ERB from .txt file

I built a .erb file that has a bunch of variables listed in it. 我建立了一个.erb文件,其中列出了一堆变量。

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

Then I have a text file with the variables: 然后我有一个带有变量的文本文件:

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

I need to take the variables from the text file and insert them into the .erb template. 我需要从文本文件中获取变量,并将其插入.erb模板。 What is the proper way to do this? 正确的方法是什么? I am thinking just a ruby script, rather than an entire rails site. 我在想的只是一个红宝石脚本,而不是整个Rails网站。 It is only for a small page, but needs to be done multiple times. 它仅用于一小页,但需要多次执行。

Thanks 谢谢

I would skip the txt file, and instead go with a yml file. 我会跳过txt文件,而是使用yml文件。

Check this site out for a little more info on how to do it: http://innovativethought.net/2009/01/02/making-configuration-files-with-yaml-revised/ 请访问此网站,以获取有关操作方法的更多信息: http : //innovativethought.net/2009/01/02/making-configuration-files-with-yaml-revised/

I think a lot of people have come at this from the "how do I get the values out of where they are stored?" 我认为很多人来自“如何从存储的值中获取价值?” and have ignored the other half of the question: "How do I replace <%= intro1 %> with some Ruby variable I have in memory? 并忽略了问题的另一半:“如何用内存中的一些Ruby变量替换<%= intro1 %>

Something like this should work: 这样的事情应该起作用:

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

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

the binding thing here means that every local variable can be seen inside by ERB when it's rendered. 这里的binding是指,每个局部变量在呈现时都可以被ERB看到。 (Technically, it's not just variables, but methods available in the scope, and some other things). (从技术上讲,它不仅是变量,还包括范围内可用的方法,以及其他一些东西)。

I agree about YML. 我同意YML。 If you really want (or have) to use a text file, you can do something like that : 如果您确实想要(或必须)使用文本文件,则可以执行以下操作:

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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM