简体   繁体   中英

pass an array from pug (jade) to jquery script

I have a array fields which contain a list of strings:

var fields = ['foo', 'bar', 'zed'];

I pass it to pug from express like this:

app.get('/some_route', function(req, res) {

    res.render('some_view', { fields: fields });

});

Now I want to use that array inside jquery script, I already try:

<script>
    $( document ).ready(function() {
        var fields = #{fields};
        // return: var fields = foo,bar,zed;
    });
</script>

and:

<script>
    $( document ).ready(function() {
        var fields = JSON.parse(#{fields});
        // return: var fields = JSON.parse(foo,bar,zed);
    });
</script>

thanks

JSON-encode it an put it in an attribute somewhere, like on the <script> itself:

script(id='field-source', data-fields=JSON.stringify(fields)).
    $(document).ready(function () {
        var fields = JSON.parse($('#field-source').data('fields'));
    });

It's possible to put it directly into the script with some careful escaping¹ (JSON-encoding is not enough!), but not worth the effort when attributes already work so reliably.

¹ You start by JSON-encoding, then make it safe for the JavaScript context by replacing U+2028 and U+2029 with \\u202[89] , then make it safe for the HTML context by replacing < with \\x3c . Replacing only </ is not enough, as <!-- can also mess with parsing in certain contrivable ways.

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