微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ruby-on-rails – Rails:在后处理器中渲染视图内容(模型/助手问题)

我有一个网络应用程序,我也有一个非常复杂的博客类型.对于这个博客,除了自制的标记语言之外,我还使用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]]是我自己的标记语言,很酷的是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."

“apple”部分是从视图部分获取的.

ApplicationHelper中的方法使用例如:
– render partials / blog_post / product_item_with_pic
– RedCarpet标记

我在标记/未处理状态下编写所有文章/博客文章,但在我发布并加载render_content()时,预处理此内容是完全合理的:before_save.

问题

基本上,我想使用:来自BlogPost和Article模型的before_save,但后来我遇到了尝试从模型中做帮助的东西的问题,这一切都变得混乱.

我试过用:

ApplicationController.helpers.render_content(@blog_post.unprocessed_content)

但后来它找不到像/ blog_post / product_item_with_pic这样的视图部分.感觉就像我会继续碰到这样的问题.

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

我的问题

>解决这个问题最优雅的方法是什么?
>如果没有一个方法,至少,当我从模型中调用ApplicationHelper时,如何访问partials?

解决方法

我不确定我完全理解你想要的东西.但是要在标准流程之外使用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获取有关如何在渲染器内提供帮助的信息.

原文地址:https://www.jb51.cc/ruby/269761.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐