[英]session variable is not recognized anymore after migrating js code to assets/javascripts in rails app
I moved some javascript that was in a content_for(:after_js) at the end of an html page to a proper js file inside my assets/javascripts folder in my rails app. 我将html页面末尾的content_for(:after_js)中的一些javascript移到了我的rails应用程序中asset / javascripts文件夹内的适当js文件中。 I created a js.erb file that looks like this : 我创建了一个js.erb文件,看起来像这样:
<% if session[:user_role] == "asso" %>
<%= render "javascripts/select_bar/_select_bar_asso.js"%>
<% else %>
<%= render "javascripts/select_bar/_select_bar_host.js"%>
<% end %>
but now I always get the error : 但是现在我总是得到错误:
undefined local variable or method `session' for #<#:0x007feb90e24400>. #<#:0x007feb90e24400>的未定义局部变量或方法'session'。
It was working fine when the js was in the content_for(:after_js) at the end of my html.erb file and it was ok with the session variable. 当js位于html.erb文件末尾的content_for(:after_js)中时,它工作正常,并且可以使用会话变量。
What did I do wrong with my javascript migration ? 我的JavaScript迁移有什么错?
You should pass the session variable as local variable to the partial, take a look here and search for section 3.4.4 Passing Local Variables . 你应该在会话变量作为局部变量传递到局部,看看这里 ,搜索第3.4.4节传递局部变量 。
To simplify, this is how you should render your js partial: 为简化起见,这是您应如何部分渲染js的方法:
<%= render partial: "my_js", locals: {session: session} %>
Your partial should remain the same. 您的局部应该保持不变。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.