简体   繁体   English

如何将样式(css)和 js 添加到车把文件?

[英]How to add styles(css) and js to handlebar files?

I want to add styles and js to my handlebar files.我想将样式js添加到我的车把文件中。 I tried looking for different places but still not able to find a solution.我尝试寻找不同的地方,但仍然无法找到解决方案。 I tried using partials to store the stylesheet tags then adding those partials to handlebar but that too didn't worked.我尝试使用部分来存储样式表标签,然后将这些部分添加到车把,但这也不起作用。 (Or if there is any other templating engine that provides much better css support, that too will work for me) Please Help! (或者,如果有任何其他模板引擎提供更好的 css 支持,那也适用于我)请帮助!

styles.hbs (partial file) style.hbs(部分文件)

<link rel="stylesheet" href="./../css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="./../css/main.css">

server.js服务器.js

const express = require('express');
const hbs = require('hbs');

var app = express();

app.set('view engine', 'hbs');
hbs.registerPartials(__dirname + '/views/partials');

app.get('/', (req, res) => {
    res.render('index.hbs');
});

app.listen(3000, ()=>{
    console.log('Server is up at port 3000');
});

index.hbs索引.hbs

<!DOCTYPE html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Home Page</title>

    {{> styles}}
  </head>
  <body>
   ...
  </body>
</html>

This is an old question but still confusing.这是一个老问题,但仍然令人困惑。 Here is the most effective way to use different css file in your views:这是在视图中使用不同 css 文件的最有效方法:

main.hbs (Your base layout) main.hbs(您的基本布局)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="mainstyle.css">
    <!-- mainstyle.css will be effective in all pages-->
    {{{customstyle}}}
    <title>{{title}}</title>
</head>
<body>
    {{body}}
</body>
</html>

Please pay attention {{{customstyle}}} line in main.hbs请关注{{{customstyle}}}符合main.hbs

app.js应用程序.js

...
app.use((req, res) => {
    res.status(404).render("404page", {title:"404 not found",
    customstyle: `<link rel="stylesheet" href="/css/customstyle.css">`});
});
...

Thats it.就是这样。 As you know, {{{ }}} renders as html code, but {{ }} renders as only text in handlebars.如您所知, {{{ }}} 呈现为 html 代码,但 {{ }} 仅呈现为车把中的文本。 customstyle passes as an argument to main.hbs layout file. customstyle作为参数传递给main.hbs布局文件。 We used three curly brackets in main.hbs file, because of we wanted to process the argument we send as html code.我们在 main.hbs 文件中使用了三个大括号,因为我们想处理我们作为 html 代码发送的参数。 In this way, customsytle.css file added only when 404page viewed.这样,customytle.css文件只在404页面查看时添加。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM