ruby inside javascript block [slim template]

后端 未结 3 776
青春惊慌失措
青春惊慌失措 2021-01-01 10:47

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

javascript:
  var config = {
      common_value_1 : 1, 
      common_value_2 : 2 
  };
           


        
相关标签:
3条回答
  • 2021-01-01 11:07

    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}
      };
    

    ** Update below **

    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
    

    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'
    

    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.

    0 讨论(0)
  • 2021-01-01 11:14

    You have 2 options:

    1. Use a ruby section

    This scenario is better for complex code.

    I have a ruby object that I want to make a JSON. So, inside my slim file I'll create a ruby section:

    ruby:
    
      myObject = @object.to_json.html_safe
    

    Pay attention to html_safe: it's important to not escape double quotes.

    Then you can use myObject inside javascript section:

    javascript:
    
      var data = #{myObject};
    

    2. Use double curly braces

    For simple cases, use the double curly braces inside the javascript section, like stated in @fphilipe answer:

    javascript:
    
      var data = #{{@object.to_json}};
    
    0 讨论(0)
  • 2021-01-01 11:18

    In pure Slim you don't have raw nor html_safe. In those cases, simply use double curly braces as documented here:

    javascript:
      var data = #{{ JSON.dump([{x: 1, y:2}]) }};
    
    0 讨论(0)
提交回复
热议问题