[英]Puppet .erb template: syntax error, unexpected $end, expecting ')' (or: inserting variables declared in .erb into text after end of code)
[英]Inserting variables into ERB from .txt file
我建立了一个.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网站。 它仅用于一小页,但需要多次执行。
谢谢
我会跳过txt文件,而是使用yml文件。
请访问此网站,以获取有关操作方法的更多信息: http : //innovativethought.net/2009/01/02/making-configuration-files-with-yaml-revised/
我认为很多人来自“如何从存储的值中获取价值?” 并忽略了问题的另一半:“如何用内存中的一些Ruby变量替换<%= intro1 %>
?
这样的事情应该起作用:
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看到。 (从技术上讲,它不仅是变量,还包括范围内可用的方法,以及其他一些东西)。
我同意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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.