Skip to content
Advertisement

How to write multi-line scripts in Pug and Facebook JS SDK

I’m trying to include a multi-line JavaScript function inside the script tag within my layout pug template. It needs to run in the script tag, i.e. it has to be done this way and cannot be passed into the template as a value, since it’s client-side logic within a node app.

This is the equivalent in vanilla HTML:

<script>
  window.fbAsyncInit = function() {
    FB.init({
      appId            : '1111111',
      autoLogAppEvents : true,
      xfbml            : true,
      version          : 'v5.0'
    });
  };
</script>
<script async defer src="https://connect.facebook.net/en_US/sdk.js"></script>

Since I’m using pug and not plain HTML I can’t get the formatting right and it doesn’t work. The pug docs have only very basic examples such as:

 script
      include script.js

And

  script(src='/javascripts/jquery.js')
  script(src='/javascripts/app.js')

This is my current pug file and my latest attempt to get it to work.

layout.pug

doctype html
html
  head
  body
  script
    //works - just testing
    - const x = 1
    //works - just testing
    - function test(){console.log('test')}
    //error - not a real error. Seems like syntax
    // Content Security Policy: The page’s settings blocked the loading of a resource at http://localhost:3000/favicon.ico
    - function testWrapper(){
        window.fbAsyncInit = function() {
          FB.init({
            appId            : '1111111',
            autoLogAppEvents : true,
            xfbml            : true,
            version          : 'v4.0' 
          });
        }
      }
    - testWrapper()
  // not sure if this is working, but I don't think so.
 script(async defer src="https://connect.facebook.net/en_US/sdk.js")

How can I get this to work?

This is the Facebook JS SDK that I am trying to use here.

Note: I suggest this is not a duplicate of this due to the slightly more involved nature of the JS code being inserted in the script tag.

Advertisement

Answer

I think I solved it using my very first solution attempt from 2 hours ago. It didn’t work then but the spacing must have been off and thrown an error, but also it seems to need that script. to work, so it was not only spacing. Now I get 200s to the FB SDK so it must be working.

Include SDK code in pug like this I think:

script. 
      window.fbAsyncInit = function() {
        FB.init({
          appId            : '111111',
          autoLogAppEvents : true,
          xfbml            : true,
          version          : 'v5.0'
        });
      };
 script(async defer src="https://connect.facebook.net/en_US/sdk.js")

Note: I want to give credit for this solution to this Stack Overflow post. I didn’t see this script. in the pug docs so I appreciate @Felipe-sabino for pointing me to it.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement