从 yaml 文件读取一些数据并在 erb 页面中使用它的正确方法是什么?

发布于 2024-09-08 19:35:09 字数 302 浏览 0 评论 0原文

我正在使用 Rails 来构建一个网站。

我有一个 yaml 文件包含一些颜色,它是 config/colors.yml

---
- white
- red
- blue
- yellow
- ...

并且,有一个 erb 文件 app/views/users/setting.html.erb,其中将需要 config/colors.yml 中的数据,并将它们放入标签中。

我不知道读取 yaml 文件的正确方法是什么。我可以读取一次并将它们存储在内存中,还是应该在每次请求页面时读取它?

I'm using rails to build a website.

I have a yaml file contails some colors, which is config/colors.yml

---
- white
- red
- blue
- yellow
- ...

And, there is an erb file app/views/users/setting.html.erb, which will need the data in config/colors.yml, and put them in a tag.

I don't know what's the correct way to read the yaml file. Can I read once and store them in memory, or I should read it each time the page is requested?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

纸伞微斜 2024-09-15 19:35:09

使用以下内容创建一个 config/initializers/load_colors.rb 初始值设定项文件:

COLORS = YAML.load_file("#{Rails.root}/config/colors.yml")

这将在 Rails 应用程序启动时将配置文件的内容加载到 COLORS 变量中。然后,您可以使用 COLORS['section_name']['white'] 等从应用程序中的任何位置访问颜色。例如,您可以这样做:

<h1 style="color: <%= COLORS['h1']['blue'] %>;">Main Heading</h1>

- 尽管在视图中使用像这样的内联样式template 并不是一个很好的实践,但它可以让您了解用法。

Create a config/initializers/load_colors.rb initializer file with these contents:

COLORS = YAML.load_file("#{Rails.root}/config/colors.yml")

This will load the contents of the configuration file into the COLORS variable when the Rails application starts. Then you can access the colours from anywhere within the application using COLORS['section_name']['white'] etc. For example, you could do:

<h1 style="color: <%= COLORS['h1']['blue'] %>;">Main Heading</h1>

—Although using an inline style like this within a view template isn't really good practice, but it gives you an idea of the usage.

零崎曲识 2024-09-15 19:35:09

如果颜色永远不会改变,则可以缓存它们。请按照此 DZone 教程进行操作。

Google 的第三个结果:ruby yaml 教程

If the colors never change, it's okay to cache them. Follow this DZone tutorial.

3rd result for Google: ruby yaml tutorial.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文