Rails 5在本地渲染中设置实例变量

时间:2017-01-30 21:14:24

标签: ruby-on-rails ruby-on-rails-5 wicked-pdf

我有一些复杂的PDF生成逻辑,需要在控制器外部渲染视图,然后将HTML传递到//default mode is implicitly defined by (or in) ANTLR4 VARIABLE : 'variable' (' ')* ',' -> mode(mode_VariableName); ... mode mode_VariableName; //define token with anything ending with comma, many ways to do this... fragment varNameFrag: [a-zA-Z_0-9]; VARIABLE_NAME: varNameFrag varNameFrag* (' ')* ',' -> mode(mode_varDesc); mode mode_varDesc; //similar again for variable description VAR_DESC: //I'll write just a comment here but should more or less match anything except END_VAR: '!>>' -> mode(DEFAULT_MODE)

WickedPDF

这一切在Rails 4上运行正常但在我们升级到Rails 5时已停止工作。

我们在此处设置的所有实例变量最终都以ActionView::Base.send(:define_method, :protect_against_forgery?) { false } av = ActionView::Base.new av.view_paths = ActionController::Base.view_paths income_statement_html = av.render :template => "reports/income_statement.pdf.erb", :layout => 'layouts/report.html.erb', locals: {:@revenue_accounts => revenue_accounts, :@expense_accounts => expense_accounts, :@start_date => start_date, :@end_date => end_date, :@business => business} 在视图中。还有一种方法可以像这样从渲染调用中设置实例变量吗?

2 个答案:

答案 0 :(得分:5)

Rails 5引入了ActionController::Base.render,允许您这样做:

rendered_html = ApplicationController.render(
  template: 'reports/income_statement',
  layout: 'report',
  assigns: {
    revenue_accounts: revenue_accounts,
    expense_accounts: expense_accounts,
    start_date: start_date,
    end_date: end_date,
    business: business
  }
)

然后您可以将其传递给WickedPDF:

WickedPdf.new.pdf_from_string(rendered_html)

You can read more about .render and using it with WickedPDF, as well get some examples of how to extract this functionality into reusable objects on this blog post

答案 1 :(得分:-1)

ActionView::Base有一个方法assign,可以调用它来设置实例变量。

    av.assign({revenue_accounts: revenue_accounts,
           expense_accounts: expense_accounts,
           start_date: start_date,
           end_date:  end_date,
           business: business})

income_statement_html = av.render :template => "reports/income_statement.pdf.erb", :layout => 'layouts/report.html.erb'