express-handlebars模板未在静态路由上加载CSS样式

时间:2019-02-19 08:02:00

标签: node.js express express-handlebars

我有一组不同的路由,都使用相同的模板main,但是任何路由都仅距离基本路由/一个,而CSS却适用,但超出此范围的任何路由都将不包含CSS。 / p>

因此app.get('/profile)将使用CSS渲染,但是app.get('/profile/edit')不会。

据我所知,此行应适用于它下面设置的所有路由,所以我不确定为什么这行不通。

在server.js中

  app.use(express.static(__dirname + "/public"));
  //Many different routes
  //...
  //...

    //renders with CSS successfully
    app.get("/profile", (req,res) => {
      res.render('profile', {
        layout: "main",
        cause: {
          title: title
        },
        csrfToken: req.csrfToken
      });
    });

 //this is the route that renders without CSS
    app.get("/profile/edit", (req,res) => {
      res.render('edit', {
        navItems: [
          {name: 'See your fellow supporters',
          link: "/signatures"}
        ],
        layout: "main",
        cause: '',
        csrfToken: req.csrfToken
      });
    });

车把模板

   //edit.handlebars
    <h2>Change your details</h2>
    <form method="POST">
    <input type="text" name="firstName" placeholder="first name">
    <label for="firstName">First Name</label>

    <input type="text" name="lastName" placeholder="last name">
    <label for="lastName">Last Name</label>

    <input type="email" name="email" placeholder="e-mail">
    <label for="email">E-mail</label>

    <input type="password" name="password" placeholder="password">
    <label for="password">Password</label>

    <input type="text" name="age" placeholder="age">
    <label for="age">Age</label>

    <input type="text" name="city" placeholder="city/town">
    <label for="city">City or Town</label>

    <input type="text" name="homepage" placeholder="homepage or social media">
    <label for="homepage">Homepage</label>

    <input type="hidden" name="_csrf" value="{{csrfToken}}">
    <input  id="formButton" type="submit" name="submit" value="Update">
  </form>


//profile.handlebars
          <h2>Let people know that you support: {{>cause}}</h2>
      <form method="POST">
        <input type="text" name="age" placeholder="age">
        <input type="text" name="city" placeholder="city/town">
        <input type="text" name="homepage" placeholder="homepage or social media">
        <input type="hidden" name="_csrf" value="{{csrfToken}}"
        <input  id="formButton" type="submit" name="submit" value="continue">
      </form>

2 个答案:

答案 0 :(得分:1)

确保在main.handlebars中,style.css的链接如下:

href="/css/styles.css"

而不是

href="css/styles.css"

答案 1 :(得分:0)

server.js中,您可以使用:

app.engine('hbs', expressHandlebars({
 defaultLayout: 'main',
 extname: '.hbs',
 layoutsDir: path.join(__dirname, 'layouts')
}))

这将要求您将main.hbs放在layouts文件夹中。

那应该可以解决您的问题。