如何确保javascript位于express-Handlebars模板中的代码底部?

Bag*_*yer 4 html jquery templates node.js handlebars.js

我问过玉模板的同一个问题.但我现在想用把手.主要原因是它的html对我来说更容易.

这是我的视图文件夹结构:

views 
   |--- home.handlebars
   |--- layouts
          |---- main.handlebars
Run Code Online (Sandbox Code Playgroud)

我的布局是:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>{{title}}</title>
    <link rel="stylesheet" href="/stylesheets/style.css">
</head>
<body>
    {{{body}}}

    <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
    <script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>

</body>
</html>
Run Code Online (Sandbox Code Playgroud)

jquery脚本在我的{{body}}之后加载.

这是我的主页模板:

<p>This is my home page</p>

<script type="application/javascript">
    $(function() {
        alert( "ready!" );
    });
</script>
Run Code Online (Sandbox Code Playgroud)

如您所见,我正在尝试在最后加载脚本.但不幸的是,它仍然在jquery脚本之前,因此我的脚本永远不会被调用.我的问题是,有没有像我在这个问题中为jade模板所做的那样(最后加载我自己的脚本)?谢谢

Bag*_*yer 11

我最后通过使用部分找到了解决方案.这是我的app.js:

var exphbs = require('express-handlebars');

var app = express(),
    hbs = exphbs.create({

        defaultLayout:'main',
        helpers: {
            section: function(name, options){ 
                if(!this._sections) this._sections = {};
                this._sections[name] = options.fn(this); 
                return null;
            } 
        }    
    });

app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars');
Run Code Online (Sandbox Code Playgroud)

我的布局文件main.handlebars:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>{{title}}</title>
    <link rel="stylesheet" href="/stylesheets/style.css">
    {{{_sections.style}}}
</head>
<body>
    {{{body}}}

    <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
    <script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
    {{{_sections.script}}}
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

我的模板文件home.handlebars:

<p>This is my home page</p>

{{#section 'script'}}

<script type="application/javascript">
    $(function() {
        alert( "I'm ready!" );
    });
</script>

{{/section}}
Run Code Online (Sandbox Code Playgroud)

一切都与我在我的玉模板中完全一样.唯一的额外工作是我必须在我的app.js文件中使用帮助器功能.