简体   繁体   中英

Use a passed variable in an external Javascript file

I'm passing two variables to my front end like this

res.render("mypage", {data: data});

Using the data within my variable, I want to build some HTML elements and do some data visualization using charts. I can of course just use my templating software (EJS) and write a whole lot of javascript within the HTML file itself, but that doesn't sound sensible.

I searched around stackoverflow and the general solution seems to be to put it into a global variable and then load in the external js file so it has access to it, so on my front end I would have this

    <head>
        <title>Cool Site</title>
        <script>
            var data = <%- data %>;
        </script>
        <script src="/fun.js"></script>
    </head>

The problem is that VSCode itself says Expression Expected for my <%- and %> parts, and when I try to access the variable within my fun.js file, it says Data is not defined and also says SyntaxError: Unexpected token .

Any ideas on how I can properly access the data?

EJS is simply a templating language. It spits out text. It will interpret the following:

<script>
  var data = <%- data %>;
</script>

...sort of like:

`<script>
  var data = ${data};
</script>`

So what does <%- data %> mean? It means take the raw value of the expression and output it to the result. Since data is an Object, it's most likely calling toString on it, and .toString() for an Object by default is the string [Object object] , making your JavaScript the following, which has a syntax error:

<script>
  var data = [Object object];
</script>

Your easiest workaround would be to serialize your data as JSON, which is intepretable within JavaScript as an object literal:

<script>
  var data = <%- JSON.stringify(data) %>;
</script>

...though you do have to be careful about edge conditions like where your data may contain a </script> string, in which case it'll prematurely close your script tag. Fortunately there are many packages out there for a safer version of JSON stringifying for output on an HTML page. Use a safer stringifying library if your data can contain arbitrary user strings; otherwise you've got a script injection vulnerability.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM