有没有一种方法在使用nodejs/express和EJS时后期添加CSS/JS?

11

我正在使用Node.js/Express的EJS模板引擎,想知道是否可以在index.ejs文件(而不是layout.ejs文件)中添加其他CSS或JavaScript文件。

layout.ejs

<!DOCTYPE html>
<html>
  <head>
    <title><%= title %></title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
    <link rel='stylesheet' href='/stylesheets/smoothness/jquery-ui-1.8.14.custom.css' />
  </head>
  <body>
    <%- body %>
  </body>
</html>

index.ejs

<h1><%= title %></h1>
<p>Welcome to <%= title %></p>
我不想在每个模板中都添加第二个CSS文件,只想在index.ejs中添加,有什么方法可以实现吗?
5个回答

20

在这里找到了解决方案:Node.js with Express: Importing client-side javascript using script tags in Jade views?

虽然使用的是 Jade 而不是 EJS,但都可以使用。以下是适用于 express 2.4.0 的一些代码片段。

您需要将以下“helpers”添加到您的 app.js 中。

app.helpers({
  renderScriptsTags: function (all) {
    if (all != undefined) {
      return all.map(function(script) {
        return '<script src="/javascripts/' + script + '"></script>';
      }).join('\n ');
    }
    else {
      return '';
    }
  }
});

app.dynamicHelpers({
  scripts: function(req, res) {
    return ['jquery-1.5.1.min.js'];
  }
});

layout.ejs的外观如下所示:

<!DOCTYPE html>
<html>
  <head>
    <title><%= title %></title>
      <link rel='stylesheet' href='/stylesheets/style.css' />
      <%- renderScriptsTags(scripts) %>
  </head>
  <body>
    <%- body %>
  </body>
</html>

如果您没有将任何脚本添加到脚本数组中,则只会包含'jquery-1.5.1.min.js' - 如果您想要向子页面添加文件,您可以像这样操作:

test.ejs

<% scripts.push('jquery-ui-1.8.14.custom.min.js', 'jquery.validate.min.js') %>

<h1><%= title %></h1>
<p>I'm a template with 3 js files in the header</p>

就是这样。


如果你恰好有expressjs > 3.x.x,请阅读下面的答案获取可工作的代码。感谢pkyeck! :) - Henrik Peinar

11

由于Express> 3中已经移除了helpers和dynamicHelpers,因此我重写了pkyeck的代码,以便其在Express 3中正常工作。

因此,在app.js中,请使用此代码代替helpers / dynamicHelpers。将其他所有内容保留不变。

app.locals({
    scripts: [],
  renderScriptsTags: function (all) {
    app.locals.scripts = [];
    if (all != undefined) {
      return all.map(function(script) {
        return '<script src="/javascripts/' + script + '"></script>';
      }).join('\n ');
    }
    else {
      return '';
    }
  },
  getScripts: function(req, res) {
    return scripts;
  }
});

9
在app.js中添加以下行:
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/public')); // This line.

在layout.ejs文件中:
<!DOCTYPE html>
<html>
  <head>
    <title>Authentication Example</title>
    <link rel="stylesheet" href="/stylesheets/style.css"/>
    <script src="/javascripts/jquery.js"></script>    
  </head>
  <body>
    <%- body %>
  </body>
</html>

In index.ejs or login.ejs:

<h1>Login</h1>
<form method="post" action="/login">
  <p>
    <label>Username:</label>
    <input type="text" name="username">
  </p>
  <p>
    <label>Password:</label>
    <input type="text" name="password">
  </p>
  <p>
    <input type="submit" value="Login">
  </p>
</form>
<script src="/javascripts/test.js"></script> <!-- Second Script -->

在test.js文件中:

$(document).ready(function() {
    try{
        alert("Hi!!!");
    }catch(e)
    {
        alert("Error");
    }
});

问候。


3

感谢@asprotte为express 4.x提供此内容。您测试过了吗?因为对我来说似乎没用。所以我对您的代码进行了一些更改,以下是它们:

将此放入app.js文件中

app.locals.scripts = [];
app.locals.addScripts=function (all) {
app.locals.scripts = [];
    if (all != undefined) {
        app.locals.scripts =  all.map(function(script) {
            console.log(script);
            return "<script src='/js/" + script + "'></script>";
        }).join('\n ');
    }

};
app.locals.getScripts = function(req, res) {
    return app.locals.scripts;
};

然后在模板文件中放入以下内容(我这里使用的是ejs模板):
<% addScripts(['cart.js']) %>

在布局文件中,我们需要在页面底部添加这些

1

感谢pkyeck解释这个选项!

在Express 4.x中,app.locals是一个对象。这是pkyeck的答案重写后在Express 4.x中的工作方式:

app.locals.scripts = [];
app.locals.addScripts=function (all) {
    app.locals.scripts = [];
    if (all != undefined) {
        return all.map(function(script) {
            return "<script src='/javascripts/" + script + "'></script>";
        }).join('\n ');
    }
    else {
        return '';
    }
};
app.locals.getScripts = function(req, res) {
    return scripts;
};


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接