【问题标题】:How to include an external JavaScript file in Haml如何在 Haml 中包含外部 JavaScript 文件
【发布时间】:2020-09-25 15:59:42
【问题描述】:

我想使用外部 JavaScript 和 jQuery 文件动态添加样式和函数,但它不断抛出错误。

Ruby 代码是:

# myapp.rb
require 'sinatra'
require 'sinatra/reloader'
require 'haml'

get '/' do
    @contacts = [
        {
            name: "Petit",
            class: "K1"
        }
    ]

    haml :index
end

get '/about-us' do
    haml :about
end

Haml 代码是:

!!!
%html
    %head
        = javascript_include_tag "actions"

    %body
        %h1#title.titles
            This is a page title

        %ul
            - @contacts.each do |contact|
                %li
                    = "#{contact[:name]}'s class is #{contact[:class]}"

        %a{ href: "/about-us"}
            About

这行似乎是问题所在:

= javascript_include_tag "actions"

错误是当我在浏览器中运行应用程序时:

NoMethodError at /
undefined method `javascript_include_tag' for #<Sinatra::Application:"some hex address here">

没有那行代码,它运行良好,嵌入的 JavaScript 也可以工作。我无法链接外部 JavaScript 文件。

【问题讨论】:

    标签: javascript jquery ruby sinatra haml


    【解决方案1】:

    当你的目录看起来像这样时:

    ruby-web/
    | public/
    |-| css/
    |-|-| styles.css
    |
    |-| javascript/
    |-|-| jquery-3.5.1.min.js
    |-|-| actions.js
    |
    | views/
    |-| index.haml
    |-| about.haml
    | my-app.rb
    

    您的 Ruby 代码如下所示:

    # myapp.rb
    require 'sinatra'
    require 'sinatra/reloader'
    require 'haml'
    
    get '/' do
        haml :index
    end
    
    get '/about-us' do
        haml :about
    end
    

    您的index.haml 将成为您连接到服务器时显示的根页面,因此您的index.haml 代码应如下所示:

    !!!
    %html
        %head
            /Styles :
            %link{:href => "css/styles.css", :type => "text/css"}
            /Scripts :
            %script{:src => "javascript/jquery-3.5.1.min.js", :type => "text/javascript"}
            %script{:src => "javascript/actions.js", :type => "text/javascript"}
    
        %body
            %h1#title
                Equations
    
            %div#about
                %footer#footer
                    %a{ href: "/about-us"}
                        About
    

    注意Haml 代码中的%link%script 标签,并查看:src:href 中给出的路径。

    它是:

    :src => "javascript/actions.js"
    

    :href => "css/styles.css" 
    

    不是:

    :src => "public/javascript/actions.js"
    

    :href => "public/css/styles.css"
    

    即使脚本和样式位于 public 文件夹中。

    也不:

    :src => "../public/javascript/actions.js" 
    

    :href => "../public/css/styles.css"
    

    即使脚本和样式位于../public/javascript/../public/css/ 相对于index.haml.

    现在你有一个包含脚本和样式的公共文件夹,你可以用上面提到的方法链接到它们。

    【讨论】:

    • 恭喜您获得第一个答案。请阅读“How to Answer”及其链接页面。语法,包括拼写和标点符号,对 SO 很重要。 Stack Overflow 不是论坛或留言板,它就像一本在线参考书。这也适用于问题,并在“How to Ask”及其链接页面中有所提及。
    猜你喜欢
    • 1970-01-01
    • 2018-11-26
    • 2017-09-10
    • 1970-01-01
    • 1970-01-01
    • 2012-04-02
    • 2012-11-19
    • 2017-10-25
    • 2020-03-19
    相关资源
    最近更新 更多