【问题标题】:Application layout loads as plain text after render_to_string应用程序布局在 render_to_string 之后加载为纯文本
【发布时间】:2014-05-06 04:05:46
【问题描述】:

我正在使用 Gon gem 将一些数据从 Rails 发送到 BackBone。 我的application_controller.rb

class ApplicationController < ActionController::Base
  before_action :init_gon

  def init_gon
    gon.me = render_to_string(template: 'users/_me.json.jbuilder')
  end
end

因此,在此之后,如果我打开 Web 应用程序的任何页面,它只会将 html 显示为纯文本:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns="" xmlns="http://www.w3.org/1999/xhtml">
<head>
.....

我该如何处理?

【问题讨论】:

    标签: ruby-on-rails render-to-string


    【解决方案1】:

    我认为您的问题与将 gon 数据呈现为字符串有关。我认为你应该传递你的数据而不需要呈现一个字符串

    我对那个特定部分没有任何经验,但我以前曾广泛使用过gon。这是涵盖该主题的 RailsCast 的 sn-p:

    Gon 只是创建一个脚本标签,然后用 我们在控制器中设置的数据。如果我们要自定义 JSON 返回给客户端的 Gon 支持 RABL 和 Jbuilder 模板,这两个模板都在最近介绍过 剧集。要自定义产品列表返回的数据,我们 可以创建一个index.json.rabl文件并定义我们想要的属性 在那里返回:

    /app/views/products/index.json.rabl
    collection Product.limit(10)
    attributes :id, :name, :price
    
    /app/controllers/products_controller.rb
    class ProductsController < ApplicationController
      def index
        gon.rabl "app/views/products/index.json.rabl", as: "products"
      end
    end
    

    JBuilder

    也许这会有所帮助?有一种方法可以render GON data with jBuilder(我看到你正在使用):

    #app/controllers/application_controller.rb
    def init_gon
        gon.jbuilder template: 'users/_me.json.jbuilder'
    end
    

    https://github.com/gazay/gon/wiki/Usage-with-jbuilder

    【讨论】:

    • 我刚刚使用了你所说的 gon.jbuilder 扩展,一切正常。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-23
    • 2011-09-30
    • 2013-02-18
    • 2011-04-03
    • 2012-05-03
    相关资源
    最近更新 更多