将变量从 .txt 文件插入 ERB [英] Inserting variables into ERB from .txt file

查看:36
本文介绍了将变量从 .txt 文件插入 ERB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我构建了一个 .erb 文件,其中列出了一堆变量.

I built a .erb file that has a bunch of variables listed in it.

 <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

我需要从文本文件中取出变量并将它们插入到 .erb 模板中.这样做的正确方法是什么?我在想只是一个 ruby​​ 脚本,而不是整个 Rails 站点.只针对一个小页面,需要做多次.

I need to take the variables from the text file and insert them into the .erb template. What is the proper way to do this? I am thinking just a ruby script, rather than an entire rails site. It is only for a small page, but needs to be done multiple times.

谢谢

推荐答案

我想很多人都是从如何从存储值中取出值?"来解决这个问题的.并忽略了问题的另一半:我如何用内存中的一些 Ruby 变量替换 <%= intro1 %>?

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?

这样的事情应该可以工作:

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)

binding 这里的意思是每个局部变量在渲染时都可以被 ERB 看到.(从技术上讲,这不仅仅是变量,还有作用域中可用的方法,以及其他一些东西).

the binding thing here means that every local variable can be seen inside by ERB when it's rendered. (Technically, it's not just variables, but methods available in the scope, and some other things).

这篇关于将变量从 .txt 文件插入 ERB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆