最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

有没有办法稍后使用带有nodejsexpress的EJS添加CSSJS

运维笔记admin21浏览0评论

有没有办法稍后使用带有nodejs / express的EJS添加CSS / JS

有没有办法稍后使用带有nodejs / express的EJS添加CSS / JS

我正在使用带有nodejs / express的EJS模板引擎,我想知道是否可以在index.ejs(而不是layout.ejs)中添加另一个css或js文件

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 - 有什么方法可以做到吗?

回答如下:

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

它使用的是玉而不是EJS,但工作方式完全相同。这里有一些快递2.4.0的代码片段。

你必须在你的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>

如果你没有向scripts-array添加任何脚本,只会包含'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>

而已。

发布评论

评论列表(0)

  1. 暂无评论