首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将逻辑注入HAML中的javascript?

如何将逻辑注入HAML中的javascript?
EN

Stack Overflow用户
提问于 2012-02-02 04:00:20
回答 1查看 813关注 0票数 0

我试图添加水星编辑器,并在修改其布局的同时,建议在视图布局中添加一些javascript。显然,下面的内容不太管用,但它表达了我正在努力完成的任务的要点。您将需要查看:javascript过滤器中的部分,在该部分中,我添加了-开始if语句,这是我的意思:

代码语言:javascript
复制
  ...
  %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);
      ...

,请你提供一个例子,说明如何正确地做这件事?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-02-02 04:09:23

您可以将逻辑提取到帮助方法,然后简单地插值它们的结果。瞧一瞧。

代码语言:javascript
复制
# 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);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9107007

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档