加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 耙子任务中的render_to_string

发布时间:2020-12-16 22:29:32 所属栏目:百科 来源:网络整理
导读:我想使用Rake任务来缓存我的站点地图,以便对sitemap.xml的请求不会永远存在.这是我到目前为止 @posts = Post.all sitemap = render_to_string :template = 'sitemap/sitemap',:locals = {:posts = @posts},:layout = false Rails.cache.write('sitemap',site
我想使用Rake任务来缓存我的站点地图,以便对sitemap.xml的请求不会永远存在.这是我到目前为止
@posts = Post.all

  sitemap = render_to_string :template => 'sitemap/sitemap',:locals => {:posts => @posts},:layout => false
  Rails.cache.write('sitemap',sitemap)

但是当我尝试运行它,我得到一个错误:

undefined local variable or method `headers' for #<Object:0x100177298>

如何将模板从Rake中渲染为字符串?

解决方法

这是我如何做到的:
av = ActionView::Base.new(Rails::Configuration.new.view_path)
  av.class_eval do
    include ApplicationHelper
  end

  include ActionController::UrlWriter
  default_url_options[:host] = 'mysite.com'

  posts = Post.all

  sitemap = av.render 'sitemap/sitemap',:posts => posts
  Rails.cache.write('sitemap',sitemap)

请注意,我将模板转换为部分,以使其工作

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读