Search code examples
javascriptnode.jsexpresspug

How to add extra javascript to the head section in a Jade-based view in Node.js


I have a Node.js express web app.

The layout.jade looks like

doctype html
html
  head
    title= title
    link(rel='stylesheet', href='/stylesheets/style.css')
    block extraHeader
  body
    block content

My map.jade looks like:

extends layout
block extraHeader
    link(rel='stylesheet' href='https://unpkg.com/leaflet@1.3.1/dist/leaflet.css')
    script(src='https://unpkg.com/leaflet@1.3.1/dist/leaflet.js')
block content
    h1= title
    h2= count
    #map
    script.
        var locations = !{JSON.stringify(jsonData)};
        // Create variable to hold map element, give initial settings to map
        var map = L.map('map',{ center: [0, 0], zoom: 7});
        // Add OpenStreetMap tile layer to map element
        L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
            attribution: '© OpenStreetMap'
        }).addTo(map);

        // Add JSON to map
        for(var i = 0; i < locations.length; i++) {
            var loc = locations[i];
            L.marker([loc.lat, loc.lng]).addTo(map);
        }

I would like to include additional javascript to the section in head of the map view instead of inline script, e.g.

<head>
... ...
<script type="text/javascript">
    // DO SOMETHING
    var foo = 1;
<script>
</head>

Is there a way to accomplish this?

EDIT: My package.json looks like:

{
  "name": "app_name",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./bin/www"
  },
  "dependencies": {
    "bluebird": "^3.5.1",
    "body-parser": "^1.18.3",
    "cookie-parser": "~1.4.3",
    "debug": "~2.6.9",
    "dotenv": "^5.0.1",
    "express": "~4.16.0",
    "http-errors": "~1.6.2",
    "jade": "~1.11.0",
    "morgan": "~1.9.0",
    "nodemon": "^1.17.5",
    "pg-promise": "^8.4.4"
  }
}

Solution

  • Which version of Jade are you using ? If you are using the previous version of Jade (< 7.0), you can use the filter :javascript.

    With latest version of Jade (Pug), you can just simply use the script tag, for example:

    script(type='text/javascript').
          // Your code here
    

    More on the topic can be found: https://github.com/pugjs/pug

    Edited: If you want to include it in the header of the layout, you can just simply move the script a block that is placed inside the header tag, in your case, moving the script tag into extraHeader will do it.