如何在HAML中将逻辑注入javascript?

时间:2012-02-02 04:00:21

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1 haml

我正在尝试添加Mercury编辑器,在修改它的布局时,它建议在视图布局中添加一些javascript。显然,下面的内容不太合适,但它表达了我想要实现的目标。您将要查看:javascript过滤器中的部分,在我添加-的位置,以便为我的意思开始if语句:

  ...
  %body{ :class => "#{controller_name} #{action_name}" }
    :javascript
      var saveUrl = null; // Set to the url that you want to save any given page to.
      var options = {
        saveStyle: null,  // 'form', or 'json' (default json)
        saveMethod: null, // 'POST', or 'PUT', (create, vs. update -- default POST)
        visible: null     // if the interface should start visible or not (default true)
      };

      //<!-- Mix in any configurations provided through Rails.application.config.mercury_config -->
      - if Rails.application.config.respond_to?(:mercury_config)
        jQuery.extend(Mercury.config,
        = Rails.application.config.mercury_config.to_json.html_safe
        );
      - end

      //<!-- Mix in any options for PageEditor provided through Rails.application.config.mercury_page_editor_config -->
      - if Rails.application.config.respond_to?(:mercury_page_editor_config)
        jQuery.extend(options,
        = Rails.application.config.mercury_page_editor_config.to_json.html_safe
        );
      - end

      //<!-- Instantiate the PageEditor -->
      new Mercury.PageEditor(saveUrl, options);
      ...

您能否提供一个如何正确执行此操作的示例?

1 个答案:

答案 0 :(得分:1)

您可以将逻辑提取到辅助方法,然后简单地插入其结果。看一看。

# page_helper.rb

def mercury_config
  if Rails.application.config.respond_to?(:mercury_config)
    "jQuery.extend(Mercury.config,
       #{Rails.application.config.mercury_config.to_json.html_safe}
    );"
  end
end

def mercury_page_editor_config
  if Rails.application.config.respond_to?(:mercury_page_editor_config)
    "jQuery.extend(options,
        #{Rails.application.config.mercury_page_editor_config.to_json.html_safe}
    );"
  end
end

# your_view.html.haml

:javascript
  var saveUrl = null; // Set to the url that you want to save any given page to.
  var options = {
    saveStyle: null,  // 'form', or 'json' (default json)
    saveMethod: null, // 'POST', or 'PUT', (create, vs. update -- default POST)
    visible: null     // if the interface should start visible or not (default true)
  };

  //<!-- Mix in any configurations provided through Rails.application.config.mercury_config -->
  #{mercury_config}

  //<!-- Mix in any options for PageEditor provided through Rails.application.config.mercury_page_editor_config -->
  #{mercury_page_editor_config}

  //<!-- Instantiate the PageEditor -->
  new Mercury.PageEditor(saveUrl, options);