在条件 .js.erb 文件中使用控制器设置变量 [英] Using controller set variables in conditional .js.erb file

查看:37
本文介绍了在条件 .js.erb 文件中使用控制器设置变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个控制器,它的动作被远程击中,然后运行我的 controller_action.js.erb 文件.

I have a controller with an action that is being hit remotely, after which my controller_action.js.erb file is run.

在我的控制器操作中,我设置了一个变量 @successful = true|false(true|false 基于函数的返回值).

Within my controller's action, I am setting a variable @successful = true|false (true|false based on the return value of a function).

在我的 javascript 文件中,我想说 if @successful 并提醒操作成功或提醒操作失败.

Within my javascript file, I want to say if @successful and either alert that the action was successful or alert that it was not.

知道怎么做吗?

推荐答案

我通常说 HAML,所以这可能不完全正确:

I speak HAML usually, so this might not be exactly correct:

if(<%= @successful %>) {
  // do stuff
} else {
  // do other stuff
}

在 HAML 中,它将是:

In HAML, it would be:

:javascript
  if(#{@successful}) {
    // do stuff
  } else {
    // do other stuff
  }

或者,您可以这样做:

(ERB)

<%- if @successful %>
  // JS code if true
<%- else %>
  // JS code if false
<%- end %>

(HAML)

- if @successful
  :javascript
    // JS code if true
- else
  :javascript
    // JS code if false

第一个选项将始终在客户端呈现您的所有 JS 代码,唯一的区别是 truefalse 是否在 if 中> 子句.

The first option will always render all your JS code on the client side, the only difference being if true or false is in the if clause.

第二个选项将有条件地仅呈现真假情况下的 JS 代码.

The second option will conditionally only render the JS code for the true or false case.

这篇关于在条件 .js.erb 文件中使用控制器设置变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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