【问题标题】:Rendering just html with Rabl使用 Rabl 仅渲染 html
【发布时间】:2013-07-30 14:55:09
【问题描述】:

我试图弄清楚如何用 Rabl 渲染 just html。我有一个没有对象的 html 部分,到目前为止,我所看到的只是带有对象的部分示例。如果我在没有对象的情况下尝试它,它只会(显然)抛出一个错误。

我得到的最接近的是:

node(:content) do
    partial("api/v1/api/partials/tips")
end

Here is the documentation for Rabl.

更新

我最终只是在下面这样做。很明显吧?出于某种原因,当我第一次尝试它时它不起作用。因此,对于在 API 响应中仅发送 HTML,这很有效。

  def tips
    render partial: "api/v1/api/partials/tips"
  end

【问题讨论】:

  • "用于生成 JSON、XML、MessagePack、PList 和 BSON 的系统。" - 它没有说关于生成 HTML 的事情。为什么不使用常规的 ERB?
  • 部分是erb。我需要将 html 发送到 iOS 应用程序,我愿意接受更好的想法:)。感谢您的意见。

标签: ruby-on-rails json api rabl


【解决方案1】:

在 rabl 视图中,例如 show.v1.rabl,您可以使用以下 (rails 4.1.2) 渲染部分视图:

object @your_object

code :html do
  context_scope.controller.render_to_string(

     # from app/views/
    partial: 'path/to/show.html.erb',

     # locals (if needed)
    locals: { 
      your_object: @your_object
    }

  )
end

【讨论】:

    【解决方案2】:

    这可以通过在 Rabl 节点内渲染 ERB 模板来实现:

    object @user
    
    node(:html_content) do |user|
      @user = user
      template = Rails.root.to_s + '/app/views/api/users/show.html.erb'
      ERB.new(File.read(template)).result(self.binding)
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-12
      • 2012-02-14
      • 1970-01-01
      • 1970-01-01
      • 2014-08-22
      • 1970-01-01
      • 2012-06-03
      相关资源
      最近更新 更多