How to pass Express response object to frontend JS object

倾然丶 夕夏残阳落幕 提交于 2019-12-04 16:49:29

You must keep in mind that Handlebars' job is to return Strings. The mustache tags, {{}}, evaluate Object references as Strings so that the resultant text can be appended to the DOM or HTTP response body. The JavaScript inside your <script> tags does not get executed until it arrives on the client. There is no way for Handlebars to return an Object reference that could survive server-side rendering and eventually get assigned to a variable on the client.

[object Object],[object Object] is the result when an Array of two Objects is stringified (ie., it is the output of calling console.log(String([{}, {}])); in your browser's console.

In order to deliver JavaScript code to the client, you must construct your template to return a String with valid JavaScript in much the same way as a typical template returns valid HTML.

The long way of doing this would be something like the following:

<script>
    var viewMarkers = [
        {{#each viewModel}}
            {
                location: '{{location}}',
                lat: {{lat}},
                lng: {{lng}}
            }
            {{#unless @last}},{{/unless}}
        {{/each}}
    ];
</script>

The simpler way of achieving this would be to have JSON.stringify do the work of stringifying your Array:

res.render('coords', { viewModel: JSON.stringify(viewModel) });

Then to render the JavaScript you would need only do the following in your template:

var viewMarkers = {{{viewModel2}}};

Note that we must use triple mustaches in order not to have our quotes HTML-escaped by Handlerbars.

I have created a fiddle for your reference.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!