【问题标题】:Rails: Render view content in post-processor (model / helper issues)Rails:在后处理器中渲染视图内容(模型/助手问题)
【发布时间】:2015-11-16 20:24:29
【问题描述】:

我有一个网络应用程序,其中我也有一个相当复杂的博客类型。对于这个博客,我使用 RedCarpet 作为标记语言和自制标记语言,这非常有用。

在我自制的标记语言中,我从应用程序中调用产品视图和其他部分。我在两种不同的模型中使用它:BlogPost 和 Article。

例如,一篇博文可能是这样的:

@blog_post.unprocessed_content = "Today I would like to show you this **cool** product that we offer: [[PRODUCT#ID:123]]." 

[[PRODUCT#ID:123]] 是我自己的标记语言,cool 是 RedCarpet。我使用 ApplicationHelper 的 render_content 方法,如下所示:

processed_content = render_content(@blog_post.unprocessed_content)

哪个会输出

processed_content = "Today I would like to show you a <strong>cool</strong> product that we offer: <h3>Apple</h3><img src="apple.jpg"><p>Apple is a nice fruit.</p>. Price: 1 USD."

“苹果”部分是从视图部分中获取的。

ApplicationHelper 中的方法使用例如: - 渲染局部/blog_post/product_item_with_pic - 红地毯标记

我在标记/未处理状态下编写所有文章/博客文章,但是当我发布并在 :before_save 上加载 render_content() 时,预处理这些内容是完全有意义的。

问题

基本上,我想使用 BlogPost 和文章 model 中的 :before_save,但后来我遇到了尝试从模型中执行辅助功能的问题,这一切都变得一团糟。

我尝试使用:

ApplicationController.helpers.render_content(@blog_post.unprocessed_content)

但是它找不到像 /blog_post/product_item_with_pic 这样的视图部分。感觉就像我会一直碰到这样的问题。

现在,我有一个非常丑陋的解决方案(有效),它是在加载视图时在视图中完成预处理。基本上,在 admin::blog_post#show 我调用 render_content 然后执行保存。是的,很丑。

我的问题

  1. 解决这个问题的最优雅的方法是什么?
  2. 如果没有真正的好方法,至少,当我从模型中调用这样的 ApplicationHelper 时,如何访问部分?

【问题讨论】:

  • 不太清楚你的render_content到底做了什么。
  • 你说的很对,不是很清楚。我现在已经编辑了。

标签: ruby-on-rails view-helpers


【解决方案1】:

我不确定我是否完全理解您想要什么。但是要在标准流程之外使用 Rails 视图渲染功能,应该使用render_anywhere gem。

require 'render_anywhere'

class Article < ActiveRecord::Base
  include RenderAnywhere
  class RenderingController < RenderAnywhere::RenderingController; end

  before_save :process_content
  attr_reader :content

  private

  def process_content
    # This variable will contain resulting HTML
    @content = render(template: 'articles/article', layout: 'articles')
  end
end

阅读brief documentation,了解如何在渲染器中提供帮助器。

【讨论】:

  • 是的,我再次阅读了我的问题,但不是很清楚。我修复了它,尝试了您的解决方案,并对我自己的功能进行了相当多的调整,它起作用了。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-20
  • 2012-07-21
  • 2017-12-07
  • 2014-12-18
  • 2014-04-27
  • 1970-01-01
相关资源
最近更新 更多