如何从数据库中渲染代码并在erb文件中使其正常工作

huangapple go评论60阅读模式
英文:

How to render code from db and make it work in erb file

问题

我有一些类似以下的标记:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html 
xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" 
content="text/html; charset=utf-8">  <title>something<title><......

嵌入了类似这样的 Ruby 标签:

Hi, <%=@user.name%>

我将所有这些文件代码存储在数据库列中,现在我想让这些代码从数据库中正常工作 - 我该怎么做?

<%= @emaildetail.description %>

我尝试过使用 html_safe 但那不会使 Ruby 代码和变量正常工作。

英文:

I have some markup like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html 
xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" 
content="text/html; charset=utf-8">  <title>something<title><......

Embedded with ruby tags like this:

Hi, <%=@user.name%> 

I stored this all file code in database column, and now I want to make this code work but coming from the database - how can I do that?

<%= @emaildetail.description %>

I have tried html_safe but that doesn't make the ruby code and variables work

答案1

得分: 1

以下是翻译好的部分:

"你现在看到的ruby标签被称为ERB"

以下是一个如何使用它的简单示例。

require 'erb'

x = 42
template = ERB.new <<-EOF
  x的值是<%= x %>
EOF
puts template.result(binding)

在你的情况下,模板内容将来自数据库而不是代码,但其余部分应该仍然有效。

这将解析所有的ruby代码和变量。您仍然需要调用.html_safe来将其呈现为HTML。

英文:

The ruby tags you're seeing is called ERB

Here is a minimal example how to use it.

require &#39;erb&#39;

x = 42
template = ERB.new &lt;&lt;-EOF
  The value of x is: &lt;%= x %&gt;
EOF
puts template.result(binding)

In your case the template content would come from the database rather than from the code, but the rest should work the same.

This will resolve all the ruby code and variables. You will still have to call .html_safe on it to also render it as html.

huangapple
  • 本文由 发表于 2023年5月25日 17:17:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76330676.html
  • ruby
  • ruby-on-rails
  • ruby-on-rails-7
  • rubygems