用车把引用css和js文件的正确方法是什么? [英] What is the proper way of referencing css and js files with handlebars?
问题描述
我目前正在为我的项目使用快递和车把.这是我第一次使用把手,我无法弄清楚如何正确引用CSS和JS文件的位置
I am currently using express and handlebars for my project. It is my first time of using handlebars and I cannot figure out how to properly reference the position of my css and js files
我当前的项目结构如下
- test (root)
-views
-js
-some JS files
-css
-some css files
-layout
-main.handlebars
- servers.js (my server)
所以我在main.handlebars布局文件中进行了跟踪
so I did following in my main.handlebars layout file
<!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.
And inside {{this}}
, index.css goes in for css and index.js goes in for js.
但这会导致无法获取404 http://localhost:8000/js/index.js
错误.因此,我认为也许把手从某种程度上看起来是根源的.所以我尝试了
But this gave Cannot GET 404 http://localhost:8000/js/index.js
error. So I thought maybe handlebars look from the root somehow. so I tried
<!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>
但这在看起来正确的文件位置时出现了无法获取404 http://localhost:8000/views/js/index.js
错误.
But this gave Cannot GET 404 http://localhost:8000/views/js/index.js
error when it looks to be the correct position of the file.
在车把中引用js和css文件的正确方法是什么?
What is the correct way of referencing the js and css file in handlebars?
推荐答案
您应该创建公共目录,并且在服务器中,您可以提供静态文件,例如 images
, fonts
, CSS
文件和 JavaScript 文件,请使用Express中内置的 express.static
中间件功能.
You should create the public directory and in the server, you can serve static files such as images
, fonts
, CSS
files, and JavaScript files, use the express.static
built-in middleware function in Express.
app.use(express.static(path.join(__dirname, '/public')));
现在,您可以加载公共目录中的文件:
Now, you can load the files that are in the public directory:
<!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>
这篇关于用车把引用css和js文件的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!