Node.js with Express: Importing client-side javascript using script tags in Jade views?

Tom picture Tom · Apr 9, 2011 · Viewed 50.2k times · Source

I've got a node.js express server running with the Jade template engine.

I've got a layout jade file which imports the body of individual views like so:

!!!
html

    head
        title= title || 'Title not set.'

    body
        #header
            h1 Header.

        #content!= body //- this renders the body of an individual view

        #footer
            p Footer.

For example, the following index page:

p Welcome to the front page.

p This page serves as a now.js test.

This works fine. However, I now want to include two client-side javascript libraries specifically for this index page (and thus not very every page, which is why I cannot put it in the head of layout).

This works:

//- import jquery
script(type='text/javascript', src='./jquery-1.5.2.min.js');

//- import now.js (hosts itself)
script(type='text/javascript', src='/nowjs/now.js')

//- import the chat client
script(type='text/javascript', src='./indexChatClient.js')

p Welcome to the front page.

p This page serves as a now.js test.

However, this loads the scripts to the body of the complete page, which is not valid HTML, right?

As far as I know, the scripts should be loaded into the head if I want to do it properly, but the head section is handled by the layout file.

So, how would I properly include these client-side javascript libraries specifically for a certain view/page?

Answer

masylum picture masylum · Apr 11, 2011

You can have them on the layout and specify which libraries to load on the "controllers".

// layout.jade
!!!
html

    head
        title= title || 'Title not set.'
        -each script in scripts 
          script(type='text/javascript', src= script)
    body
        #header
            h1 Header.

        #content!= body //- this renders the body of an individual view

        #footer
            p Footer.

And your "controller":

// app.js
app.get('/', function (req, res) {
  res.render({
    scripts: ['jquery.min.js', '/nowjs/now.js']
  }
}