[node.js] How can I render inline JavaScript with Jade / Pug?

I'm trying to get JavaScript to render on my page using Jade (http://jade-lang.com/)

My project is in NodeJS with Express, eveything is working correctly until I want to write some inline JavaScript in the head. Even taking the examples from the Jade docs I can't get it to work what am I missing?

Jade template

!!! 5
html(lang="en")
  head
    title "Test"
    script(type='text/javascript')
      if (10 == 10) {
        alert("working")
      }
  body

Resulting rendered HTML in browser

<!DOCTYPE html>
<html lang="en">
<head>
  <title>"Test"</title>
  <script type="text/javascript">
    <if>(10 == 10) {<alert working></alert></if>}
  </script>
</head>
<body>
</body>
</html>

Somethings definitely a miss here any ideas?

This question is related to node.js express pug

The answer is


Use script tag with the type specified, simply include it before the dot:

script(type="text/javascript").
  if (10 == 10) {
    alert("working");
  }

This will compile to:

<script type="text/javascript">
  if (10 == 10) {
    alert("working");
  }
</script>

script(nonce="some-nonce").
  console.log("test");

//- Workaround
<script nonce="some-nonce">console.log("test");</script>

simply use a 'script' tag with a dot after.

script.
  var users = !{JSON.stringify(users).replace(/<\//g, "<\\/")}

https://github.com/pugjs/pug/blob/master/examples/dynamicscript.pug


Use the :javascript filter. This will generate a script tag and escape the script contents as CDATA:

!!! 5
html(lang="en")
  head
    title "Test"
    :javascript
      if (10 == 10) {
        alert("working")
      }
  body

No use script tag only.

Solution with |:

script
  | if (10 == 10) {
  |   alert("working")
  | }

Or with a .:

script.
  if (10 == 10) {
    alert("working")
  }

The :javascript filter was removed in version 7.0

The docs says you should use a script tag now, followed by a . char and no preceding space.

Example:

script.
  if (usingJade)
    console.log('you are awesome')
  else
    console.log('use jade')

will be compiled to

<script>
  if (usingJade)
    console.log('you are awesome')
  else
    console.log('use jade')
</script>

For multi-line content jade normally uses a "|", however:

Tags that accept only text such as script, style, and textarea do not need the leading | character

This said, i cannot reproduce the problem you are having. When i paste that code in a jade template, it produces the right output and prompts me with an alert on page-load.


THIRD VERSION OF MY ANSWER:

Here's a multiple line example of inline Jade Javascript. I don't think you can write it without using a -. This is a flash message example that I use in a partial. Hope this helps!

-if(typeof(info) !== 'undefined')
  -if (info)
    - if(info.length){
      ul
        -info.forEach(function(info){
          li= info
      -})
  -}

Is the code you're trying to get to compile the code in your question?

If so, you don't need two things: first, you don't need to declare that it's Javascript/a script, you can just started coding after typing -; second, after you type -if you don't need to type the { or } either. That's what makes Jade pretty sweet.

--------------ORIGINAL ANSWER BELOW ---------------

Try prepending if with -:

-if(10 == 10)
  //do whatever you want here as long as it's indented two spaces from
   the `-` above

There are also tons of Jade examples at:

https://github.com/visionmedia/jade/blob/master/examples/


Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`

Examples related to express

UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block jwt check if token expired Avoid "current URL string parser is deprecated" warning by setting useNewUrlParser to true MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017] npm notice created a lockfile as package-lock.json. You should commit this file Make Axios send cookies in its requests automatically What does body-parser do with express? SyntaxError: Unexpected token function - Async Await Nodejs Route.get() requires callback functions but got a "object Undefined" How to redirect to another page in node.js

Examples related to pug

Angular 4: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe' Node - how to run app.js? CSS how to make scrollable list Client on Node.js: Uncaught ReferenceError: require is not defined Change value of input placeholder via model? Set value of textbox using JQuery Change the "No file chosen": Error: Failed to lookup view in Express Loop in Jade (currently known as "Pug") template engine How to pass variable from jade template file to a script file?