我目前在我的项目中使用 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
当它看起来是文件的正确位置时出错。
在handlebars中引用js和css文件的正确方法是什么?
您应该创建公共目录,并在服务器中提供静态文件,例如images
, fonts
, CSS
文件,以及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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)