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

问题描述 投票:0回答:2

我有一些这样的标记:

<!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, <%[email protected]%> 

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

<%= @emaildetail.description %>

我已经尝试过

html_safe
但这并不能让ruby代码和变量工作

ruby-on-rails ruby rubygems ruby-on-rails-7
2个回答
1
投票

您看到的 ruby 标签称为 ERB

这是一个如何使用它的最小示例。

require 'erb'

x = 42
template = ERB.new <<-EOF
  The value of x is: <%= x %>
EOF
puts template.result(binding)

在您的情况下,模板内容将来自数据库而不是来自代码,但其余部分应该工作相同。

这将解析所有 ruby 代码和变量。您仍然需要对其调用

.html_safe
才能将其呈现为 html。


0
投票

花一些时间阅读 Rails 指南:Action Mailer 基础知识,它应该告诉你需要知道的一切。有很多方法可以实现这样的事情,但这是一个非常原始的例子:

app/models/mail_detail.rb

class MailDetail
  belongs_to :user

  validates :recipient, presence: true
  validates :custom_body, presence: true
end

app/mailers/custom_mailer.rb

class CustomMailer < ApplicationMailer
  default from: '[email protected]'

  def custom_message
    @detail = params[:maildetail]
    # You can also pass user as a param, but ideally there is a model association
    @user = @detail.user

    # Users change their email addresses, store it on your detail record
    # if you need to retain an accurate history
    mail to: @detail.recipient, subject: @detail.subject
  end
end

app/views/custom_mailer/custom_message.html.erb

<!DOCTYPE html>
<html>
  <head>
    <meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />
  </head>
  <body>
    <h1>Hi, <%= @user.first_name %></h1>
    <div><%= @detail.custom_body.html_safe %></div>
  </body>
</html>

这是一个有效的原始示例,不是关于将自定义内容生成到模板中的明确指导。

http://localhost:3000/rails/mailers/custom_mailer/custom_message

 预览您的邮件

正在发送

发送电子邮件看起来像这样:

CustomMailer.with(mail_detail: some_email_detail_record).custom_message.deliver_now

ActionMailer::Parameterized::ClassMethods#with 方法定义了可用于您的邮件程序方法的

params

或者,您可以使用命名参数来定义邮件程序方法:

def custom_message(detail:)
  @detail = detail
  @user = detail.user
  mail to: @detail.recipient, subject: @detail.subject
end

并通过以下方式发送:

CustomMailer.custom_message(detail: some_email_detail_record).deliver_now
© www.soinside.com 2019 - 2024. All rights reserved.