将Script标签和Body标签插入NodeJS Handlebars模板

时间:2018-09-13 05:18:33

标签: node.js handlebars.js express-handlebars

我的问题是是否可以将body和script标签同时注入到车把模板中。我在网上浏览过,但只发现令人困惑的教程/示例。举个例子,我已经设置了以下内容,并且工作正常:

layout.hbs:

<!DOCTYPE html>
<html>
    <head>  
    </head>
    <body>
        {{{ body }}}
    </body>
</html>

index.hbs:

<h1>test</h1>

server.js:

const express = require('express');
const hbs  = require('express-handlebars');
app.engine('hbs',hbs({extname: 'hbs'}))
app.set('view engine', 'hbs');

但是!我还想要实现的是,我还可以按照以下方式将index.hbs中的脚本添加到layout.hbs中:

layout.hbs:

<!DOCTYPE html>
<html>
    <head>
        {{{ script }}}  
    </head>
    <body>
        {{{ body }}}
    </body>
</html>

index.hbs:

<script>
    <script src="example.js" defer></script>
</script>
<body>
    <h1>test</h1>
</body>

这可能吗?如果是这样,我将需要进行哪些更改

1 个答案:

答案 0 :(得分:0)

根据您要完成的工作,我建议将脚本放入布局中。

例如:

layout.hbs:

 <!DOCTYPE html>
<html>
 <body>
 {{> nav }}
 {{{body}}}
 {{> footer }}
<script src="/js/file-validation.js"></script>
</body>
</html>

file-validation.js

(function() {
'use strict';
window.addEventListener('load', function() {
    // Fetch all the forms we want to apply custom Bootstrap validation styles to
    var forms = document.getElementsByClassName('needs-validation');
    // Loop over them and prevent submission
    var validation = Array.prototype.filter.call(forms, function(form) {
        form.addEventListener('submit', function(event) {
            if (form.checkValidity() === false) {
                event.preventDefault();
                event.stopPropagation();
            }
            form.classList.add('was-validated');
        }, false);
    });
}, false);

})();

support.hbs

 <form action="{{feedbackEmail}}"
                  method="POST" class="needs-validation" novalidate>
           <div class="form-row">
                    <div class="form-group col-md-6">
                        <label for="inputName">Name</label>
                        <input  name=name type="text" class="form-control" id="validationName" placeholder="Name" aria-describedby="inputGroupPrepend" required>
                        <div class="invalid-feedback">
                            Please enter your name.
                        </div>
                    </div>
                    <div class="form-group col-md-6">
                        <label for="inputEmail4">Email</label>
                        <input name="email" type="email" class="form-control" id="validationEmail" placeholder="You@email.com" aria-describedby="inputGroupPrepend" required>
                        <div class="invalid-feedback">
                            Please enter your email.
                        </div>
                    </div>
                </div>
              <button type="submit" class="btn btn-primary">Submit</button>
            </form>

这样,当您将部分放在一起时,它将在您对其实施过的任何.hbs文件中调用脚本。

在此示例中,此操作由支持表格上的needs-validation类完成。