我有一些复杂的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}
在视图中。还有一种方法可以像这样从渲染调用中设置实例变量吗?
答案 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)
答案 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'