ruby inside javascript block [slim template]

后端 未结 3 799
青春惊慌失措
青春惊慌失措 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: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}};
    

提交回复
热议问题