Rails:从外部控制器渲染视图 [英] Rails: Render view from outside controller

查看:35
本文介绍了Rails:从外部控制器渲染视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用视图创建 HTML 字符串.我想从不是控制器的类中呈现它.如何在控制器外使用 rails 渲染引擎?类似于 ActionMailer 的做法?

I'm trying to create an HTML string using a view. I would like to render this from a class that is not a controller. How can I use the rails rendering engine outside a controller? Similar to how ActionMailer does?

谢谢!

推荐答案

Rails 5 现在以一种更方便的方式支持这一点,可以处理创建请求和其他幕后的事情:

Rails 5 now supports this in a much more convenient manner that handles creating a request and whatnot behind the scenes:

rendered_string = ApplicationController.render(
  template: 'users/show',
  assigns: { user: @user }
)

这会呈现 app/views/users/show.html.erb 并设置 @user 实例变量,因此您无需对模板进行任何更改.它会自动使用 ApplicationController(默认为 application.html.erb)中指定的布局.

This renders app/views/users/show.html.erb and sets the @user instance variable so you don't need to make any changes to your template. It automatically uses the layout specified in ApplicationController (application.html.erb by default).

该测试显示了一些额外的选项和方法.

这篇关于Rails:从外部控制器渲染视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆