gpt4 book ai didi

ruby-on-rails - 如何在 Rails 3 中的 Controller 之外渲染模板?

转载 作者:行者123 更新时间:2023-12-03 23:38:07 25 4
gpt4 key购买 nike

我似乎无法在 Rails 3 应用程序中的 Controller 之外呈现模板。我所做的谷歌搜索很有帮助,我最终在 http://www.swombat.com/rails-rendering-templates-outside-of-a-contro 找到了一些有用的信息。 .然而,这似乎在 Rails 3 中被打破了。有没有人知道我如何修复这个方法或者知道更好的方法?

我的方法:

  def render_erb(template_path, params)  
view = ActionView::Base.new(ActionController::Base.view_paths, {})

class << view
include ApplicationHelper
end

view.render(:file => "#{template_path}.html.erb", :locals => params)
end

错误:
ActionView::Template::Error: ActionView::Template::Error
from /Library/Ruby/Gems/1.8/gems/activesupport-3.0.0/lib/active_support/whiny_nil.rb:48:in `method_missing'
from /Users/mikegerstenblatt/Desktop/bluetrain/lib/test.html.erb:17:in `_lib_test_html_erb__366962844_2173671680_68830'
from /Library/Ruby/Gems/1.8/gems/actionpack-3.0.0/lib/action_view/template.rb:135:in `send'
from /Library/Ruby/Gems/1.8/gems/actionpack-3.0.0/lib/action_view/template.rb:135:in `render'
from /Library/Ruby/Gems/1.8/gems/activesupport-3.0.0/lib/active_support/notifications.rb:54:in `instrument'
from /Library/Ruby/Gems/1.8/gems/actionpack-3.0.0/lib/action_view/template.rb:127:in `render'
from /Library/Ruby/Gems/1.8/gems/actionpack-3.0.0/lib/action_view/render/rendering.rb:59:in `_render_template'
from /Library/Ruby/Gems/1.8/gems/activesupport-3.0.0/lib/active_support/notifications.rb:52:in `instrument'
from /Library/Ruby/Gems/1.8/gems/activesupport-3.0.0/lib/active_support/notifications/instrumenter.rb:21:in `instrument'
from /Library/Ruby/Gems/1.8/gems/activesupport-3.0.0/lib/active_support/notifications.rb:52:in `instrument'
from /Library/Ruby/Gems/1.8/gems/actionpack-3.0.0/lib/action_view/render/rendering.rb:56:in `_render_template'
from /Library/Ruby/Gems/1.8/gems/actionpack-3.0.0/lib/action_view/render/rendering.rb:26:in `render'
from /Users/mikegerstenblatt/Desktop/bluetrain/app/models/generated_website.rb:45:in `render_erb'
from (irb):2

最佳答案

我做了一个 blog post和一个 gist这解释了它。

基本上你需要这样做:

class HelloWorldController < AbstractController::Base
include AbstractController::Rendering
include AbstractController::Layouts
include AbstractController::Helpers
include AbstractController::Translation
include AbstractController::AssetPaths
include ActionController::UrlWriter

self.view_paths = "app/views"

def show; end
end

接着:
HelloWorldController.new.show

将返回呈现为字符串的 View 。

关于ruby-on-rails - 如何在 Rails 3 中的 Controller 之外渲染模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3979139/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com