【问题标题】:Rails rendering template dynamically does not resolve stylesheetsRails 渲染模板动态不解析样式表
【发布时间】:2018-11-06 18:10:33
【问题描述】:

我正在使用外部 API 在 Rails 中发送电子邮件,因此需要编写自己的代码来将模板呈现为字符串。

  def html_for_template(template_name)
    template_root = "app/views/emails"
    template_path = "#{template_root}/#{template_name}"

    haml = File.open(template_path).read
    html = Haml::Engine.new(haml).render
    content = ERB.new(html).result
  end

模板内容:

%html
  %head
    %meta{content: "text/html; charset=utf-8", "http-equiv" => "Content-Type"}
    %link{"data-turbolinks-track" => "true", href: "styles.css", media: "all", rel: "stylesheet"}

问题是,生成的字符串实际上并没有解析styles.css的内容,而只是复制了文字字符串<link>...</link>,这是没用的,因为我需要生成字符串中的实际CSS内容。

我也试过了:

:css
  = MyApp::Application.assets["styles.css"].to_s.html_safe

但这会产生相同的结果:MyApp::Application.assets["styles.css"].to_s.html_safe 被逐字复制,并没有真正解决。 ApplicationController.render(template_path) 也产生相同的结果。

如何在解析样式表内容时将模板呈现为字符串?

【问题讨论】:

    标签: css ruby-on-rails ruby haml


    【解决方案1】:

    在像 :css 这样的 HAML 过滤器中,这些内容被视为字符串,您必须使用 #{something} 来运行 ruby​​ 代码。

    :css
      #{MyApp::Application.assets["styles.css"].to_s.html_safe}
    

    【讨论】:

    • 是的,这就是问题所在。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2020-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-17
    相关资源
    最近更新 更多