RHTML 到字符串 -rails

发布于 2024-09-14 02:04:29 字数 558 浏览 5 评论 0原文

在我的 Rails 应用程序中,我的模型有一个 to_html 方法。在其中一个视图中调用此方法,以便模型的属性可以正确显示,而不管它们的类如何(因为我的所有类都实现该方法)

这是一个简洁的解决方案,但有一件事让我烦恼。我需要将此 html 代码写入双引号内(作为字符串),并最终转义我在 html 代码中手动使用的其他双引号。

我希望能够使用 rhtml 文件:读取它们,评估其中最终的 ruby​​ 代码,并将结果作为带有必要转义字符的字符串返回。我给你举个例子:

下面的代码:

<label for="blabla"> <%= ruby_variable.name %> </label>

处理时应该返回我:

"<label for=\"blabla\"> name </label>"

有谁知道已经做到这一点的东西或者可以为我指出好的方向吗?我正在考虑自己编写一段代码来实现这一点。但如果有些东西已经可以工作了,我很乐意使用它。

谢谢

In my rails application my models have a to_html method. This method is called in one of the views so the model's attributes can be displayed properly regardless of their classes (because all of my classes implement that method)

That is a neat solution, but one thing bugs me. I need to write this html code inside the double quotes (as strings) and eventually escape the other double quotes that I use in my html code manually.

I'd like to be able to work with rhtml files instead: read them, evaluate the eventual ruby code in it and return the result as a string with the necessary escaped characters. I'll give you an example:

The following code:

<label for="blabla"> <%= ruby_variable.name %> </label>

when processed should return me:

"<label for=\"blabla\"> name </label>"

Does anyone know something that already does that or could point me in the good direction? I was thinking of writing a piece of code that does that myself. But if something is already out there working, I'd me happy to use it.

Thanks

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

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

发布评论

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

评论(1

最美不过初阳 2024-09-21 02:04:29

如果需要,您可以直接在视图之外使用 ERB。例如:

require 'erb'
v = 'testing123'
output = ERB.new('<label><%= v %></label>').result(binding)

will return

<label>testing123</label>

也就是说,我不完全确定为什么你需要在模型类中使用 to_html 方法,因为它打破了 Rails 很好地提供的模型、视图和控制器之间的分离。不过我会把它留给你!

You can use ERB directly outside of your views if you want. For example:

require 'erb'
v = 'testing123'
output = ERB.new('<label><%= v %></label>').result(binding)

will return

<label>testing123</label>

That said, I'm not entirely sure why you'd want a to_html method in your model classes as it breaks the separation between model, view and controller that Rails so nicely provides. I'll leave that down to you though!

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