我有一个 Web 应用程序,其中还有相当复杂的博客类型。对于这个博客,除了自制的标记语言之外,我还使用 RedCarpet 作为标记语言,这非常有用。
在我自制的标记语言中,我从应用程序中调用产品 View 和其他部分。我在两种不同的模型中使用它:BlogPost 和文章。
例如,一篇博客文章可能是这样的:
@blog_post.unprocessed_content = "Today I would like to show you this **cool** product that we offer: [[PRODUCT#ID:123]]."
[[PRODUCT#ID:123]] 是我自己的标记语言和 酷是红地毯。我使用 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."
“苹果”部分是从 View 部分中获取的。
ApplicationHelper 中的方法使用例如:
- 渲染局部/blog_post/product_item_with_pic
- RedCarpet 标记
我在标记/未处理状态下编写所有文章/博客文章,但是当我发布并在
:before_save
上加载 render_content() 时预处理这些内容是完全有意义的。 .问题
基本上,我想使用 BlogPost 和文章模型中的 :before_save ,但后来我遇到了尝试从模型中做助手的问题,这一切都变得困惑。
我尝试使用:
ApplicationController.helpers.render_content(@blog_post.unprocessed_content)
但是它找不到像/blog_post/product_item_with_pic 这样的 View 部分。感觉就像我会继续遇到这样的问题。
现在,我有一个非常丑陋的解决方案(有效),它是在加载 View 时在 View 中完成预处理。基本上,在 admin::blog_post#show 中,我调用 render_content 然后执行保存。是的,很丑。
我的问题
最佳答案
我不确定我完全理解你想要什么。但是要在标准流程之外使用 Rails View 渲染功能,应该使用 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有关如何在渲染器内部提供帮助程序的信息。
关于ruby-on-rails - rails : Render view content in post-processor (model/helper issues),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32164914/