RHTML 到字符串 -rails
在我的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果需要,您可以直接在视图之外使用 ERB。例如:
will return
也就是说,我不完全确定为什么你需要在模型类中使用 to_html 方法,因为它打破了 Rails 很好地提供的模型、视图和控制器之间的分离。不过我会把它留给你!
You can use ERB directly outside of your views if you want. For example:
will return
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!