Ivanm
Ivanm

Reputation: 129

How to pass Jade string interpolation to JS script File?

I have my Jade file like this:

script(text='text/javascript', src='/javascript/user_options.js')
    var firstName = #{firstnameDisplay};

My user_options.js:

var displayName = firstName;

I still get the 'firstName' variable as undefined. The string interpolation #{firstnameDisplay} in the Jade file is defined correctly. Any ideas or solutions? Is there a way to declare a JS variable in Jade and use it in the JS script file?

Other sources online recommended JSON, but I would prefer to just use Jade string interpolations.

Upvotes: 1

Views: 302

Answers (2)

Andro Font
Andro Font

Reputation: 356

Don't do that... generate js code that way have a bunch of drawbacks. It is preferrable to put that value in a hidden field for example or as a data-attribute in some element then in your js file you could ask for that value.

First Option

input(type="hidden", value=#{firstnameDisplay}, id="firstNameDisplay")

Second Option

div(id="firstNameDisplay", data-firstNameDisplay=#{firstnameDisplay})

then you could retrieve that value with JQuery or Vanilla js.

var displayName = document.getElementById('firstNameDisplay').value

or

var displayName  = document.getElementById('firstNameDisplay').dataset.firstNameDisplay;

Upvotes: 2

smupyknight
smupyknight

Reputation: 174

You need to try something like this

script.
    var firstName = #{firstnameDisplay};

script(text='text/javascript', src='/javascript/user_options.js')

Upvotes: 0

Related Questions