【问题标题】:What is the proper way of referencing css and js files with handlebars?使用把手引用 css 和 js 文件的正确方法是什么?
【发布时间】:2018-01-05 20:22:18
【问题描述】:

我目前正在为我的项目使用 express 和车把。这是我第一次使用把手,我不知道如何正确引用我的 css 和 js 文件的位置

我目前的项目结构如下

- test (root)
  -views
    -js
      -some JS files
    -css
      -some css files
    -layout
      -main.handlebars
  - servers.js (my server)

所以我在 main.handlebars 布局文件中做了以下操作

<!Doctype html>
<html>
<head>
    <title></title>
    {{#each css}}
        <link rel="stylesheet" href="../css/{{this}}">
    {{/each}}
</head>
<body>
    {{{body}}}
    {{#each js}}
        <script src="../js/{{this}}"></script>
    {{/each}}
</body>
</html>

{{this}} 内部,index.css 用于 css,index.js 用于 js。

但这给了Cannot GET 404 http://localhost:8000/js/index.js 错误。所以我想也许车把从根本上看。所以我尝试了

<!Doctype html>
<html>
<head>
    <title></title>
    {{#each css}}
        <link rel="stylesheet" href="views/css/{{this}}">
    {{/each}}
</head>
<body>
    {{{body}}}
    {{#each js}}
        <script src="views/js/{{this}}"></script>
    {{/each}}
</body>
</html>

但是当它看起来是文件的正确位置时,这给了Cannot GET 404 http://localhost:8000/views/js/index.js 错误。

在把手中引用js和css文件的正确方法是什么?

【问题讨论】:

    标签: javascript html css node.js handlebars.js


    【解决方案1】:

    您应该创建公共目录,在服务器中,您可以提供静态文件,例如 imagesfontsCSS 文件和 JavaScript 文件,使用 express.static Express 内置中间件功能。

    app.use(express.static(path.join(__dirname, '/public')));
    

    现在,您可以加载公共目录中的文件:

    <!Doctype html>
    <html>
    <head>
        <title></title>
        {{#each css}}
            <link rel="stylesheet" href="/css/{{this}}">
        {{/each}}
    </head>
    <body>
        {{{body}}}
        {{#each js}}
            <script src="/js/{{this}}"></script>
        {{/each}}
    </body>
    </html>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-17
      • 1970-01-01
      • 2016-02-01
      • 1970-01-01
      • 2017-03-06
      • 1970-01-01
      • 2020-12-22
      • 2018-04-28
      相关资源
      最近更新 更多