javascript 块中的 ruby​​ [slim 模板] [英] ruby inside javascript block [slim template]

查看:30
本文介绍了javascript 块中的 ruby​​ [slim 模板]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法将 ruby​​ 条件放在 javascript 块中?即

There is a way to put ruby conditions inside javascript block? i.e.

javascript:
  var config = {
      common_value_1 : 1, 
      common_value_2 : 2 
  };
  - if my_value === true # this must be a ruby condition
    config.custom_true_value_1 = "1" ;
    config.custom_true_value_2 = "#{my_value}" ;
  - else
    config.custom_false_value_1 = "1" ;
    config.custom_false_value_2 = "#{my_value}" ;

或者是否有其他解决方法可以解决此问题?因为我可以使用它的丑陋方式:

Or is there another workaround at this problem? Because the ugly way that I can use its:

javascript:
    var config = {
      common_value_1 : 1, 
      common_value_2 : 2 
    };
- if my_value === true # this must be a ruby condition
  javascript:
    config.custom_true_value_1 = "1" ;
    config.custom_true_value_2 = "#{my_value}" ;
- else
  javascript:
    config.custom_false_value_1 = "1" ;
    config.custom_false_value_2 = "#{my_value}" ;

但我不喜欢它,因为如果 config 在 if 和 else 之间有共同的值,那么我会复制我的代码并且会更大且难以维护.

But I don't like it because if config has common values between if and else then I would duplicate my code and would be much larger and hard to maintain.

更新了更好的例子

推荐答案

您可以使用类似于字符串插值的样式.请参阅下面的示例.

You can use a style similar to string interpolation. See example below.

javascript:
  var config = { 
    custom: "#{my_value ? 'truthy' : 'falsy'}",
    current_user: #{raw current_user.to_json}
  };

** 下面更新**

如果你想要更高级的配置,我建议你创建一个类,例如

If you want more advanced configuration I would recommend to create a class, for example

class ClientConfig
  attr_accessor :foo, :bar

  # .. code

  def to_json
    { foo: foo, bar: bar }.to_json
  end
end

# in view file
javascript: 
  var config = ClientConfig.new.to_json

否则你也有机会创建一个 ruby​​ 部分我在下面创建了一个例子,他可能不那么漂亮,但我工作了.

Else you also have the opportunity to create a ruby partial I've created an example below who may not be so beautiful but I works.

# template_path/_config.html.ruby
def configuration
  { foo: "Hello", bar: "World" }
end

def july_special
  { june_key: "It's June" }
end

def month_name
  Date.today.strftime("%B")
end

config = month_name == 'July' ? configuration.merge(july_special) : configuration

content_tag :script, config.to_json.html_safe

# viewfile
= render 'template_path/config'

所以我的观点是有多种方法可以做到这一点,您应该尝试找到最适合您和您的应用程序的方法.就我而言,如果我只需要一个或两个值,我将使用我的第一个示例(更新之前),否则我将使用 ClientConfig 类.

So my point is that there are multiple ways of doing this and you should try to find the way the one that suits you and your application the most. In my case, I would use my first example (before the update) if I just need one or two values else I would go for the class ClientConfig.

这篇关于javascript 块中的 ruby​​ [slim 模板]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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