![](/img/trans.png)
[英]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.