Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ensure the javascript is at the bottom of the code in express-handlebars template?

I've asked the same question for jade template. But I'd like to use handlebars now. The main reason is it's html like which is easier for me.

Here is my view folder structure:

views 
   |--- home.handlebars
   |--- layouts
          |---- main.handlebars

My layout is:

<!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>

The jquery script is loaded at the end after my {{body}}.

Here is my home page template:

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

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

As you see, I'm trying to load the script at the very end. But unfortunately it's still before the jquery script so that my script is never called. My question is if there is a way like what I did in this question for jade template (to load my own script at last)? Thanks

like image 225
Bagusflyer Avatar asked Dec 26 '22 05:12

Bagusflyer


1 Answers

I find a solution finally by using sections. Here is my 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');

My layout file 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>

My template file home.handlebars:

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

{{#section 'script'}}

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

{{/section}}

Everything is exactly the same as I did in my jade template. The only extra work is that I have to use the helpers function in my app.js file.

like image 196
Bagusflyer Avatar answered Dec 28 '22 08:12

Bagusflyer