【问题标题】:How to add styles(css) and js to handlebar files?如何将样式(css)和js添加到车把文件?
【发布时间】:2018-02-17 08:41:40
【问题描述】:

我想将 stylesjs 添加到我的车把文件中。我尝试寻找不同的地方,但仍然无法找到解决方案。我尝试使用 partials 来存储 stylesheet 标签,然后将这些部分添加到车把,但这也没有奏效。 (或者如果有任何其他模板引擎可以提供更好的 css 支持,那也适用于我) 请帮忙!

styles.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

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

<!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>

【问题讨论】:

  • 我的部分已经显示在我的模板中,所以配置没有问题。它只是没有应用到我要问的页面的样式。
  • 嘿@MohamedNadeem,你找到解决方案了吗?我也有同样的问题。。

标签: javascript node.js express handlebars.js partials


【解决方案1】:

这是一个老问题,但仍然令人困惑。这是在视图中使用不同 css 文件的最有效方法:

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>

请注意{{{customstyle}}}main.hbs中的行

app.js

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

就是这样。如您所知,{{{ }}} 呈现为 html 代码,但 {{ }} 仅呈现为把手中的文本。 customstyle 作为参数传递给 main.hbs 布局文件。我们在 main.hbs 文件中使用了三个大括号,因为我们想处理我们作为 html 代码发送的参数。这样,customsytle.css 文件只有在查看 404 页面时才添加。

【讨论】:

    猜你喜欢
    • 2017-05-24
    • 1970-01-01
    • 1970-01-01
    • 2012-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-01
    • 1970-01-01
    相关资源
    最近更新 更多