EJS客户端变量未定义

时间:2018-03-09 21:43:47

标签: javascript node.js ejs serverside-rendering

以下是我从EJS自述文件中的示例中获得的代码:

<div id="output"></div>
<script src="/js/ejs.min.js"></script>
<script>
  html = ejs.render('<%= people %>', {people: 'hello'});
  document.getElementById('output').innerHTML = html;
</script>

只有那个基本代码,我会以某种方式收到错误,

ReferenceError: /Users/owner/Dropbox/answered-client/views/pages/test.ejs:4
    2| <script src="/js/ejs.min.js"></script>
    3| <script>
 >> 4|   html = ejs.render('<%= people %>', {people: 'hello'});
    5|   document.getElementById('output').innerHTML = html;
    6| </script>
    7| 

    people is not defined
        at eval (eval at compile (/Users/owner/Dropbox/answered-client/node_modules/ejs/lib/ejs.js:549:12), <anonymous>:11:26)
        at returnedFn (/Users/owner/Dropbox/answered-client/node_modules/ejs/lib/ejs.js:580:17)
        at tryHandleCache (/Users/owner/Dropbox/answered-client/node_modules/ejs/lib/ejs.js:223:34)
        at View.exports.renderFile [as engine] (/Users/owner/Dropbox/answered-client/node_modules/ejs/lib/ejs.js:437:10)
        at View.render (/Users/owner/Dropbox/answered-client/node_modules/express/lib/view.js:135:8)
        at tryRender (/Users/owner/Dropbox/answered-client/node_modules/express/lib/application.js:640:10)
        at Function.render (/Users/owner/Dropbox/answered-client/node_modules/express/lib/application.js:592:3)
        at ServerResponse.render (/Users/owner/Dropbox/answered-client/node_modules/express/lib/response.js:1008:7)
        at app.get (/Users/owner/Dropbox/answered-client/index.js:36:7)
        at Layer.handle [as handle_request] (/Users/owner/Dropbox/answered-client/node_modules/express/lib/router/layer.js:95:5)

有什么明显的东西我不见了吗?

2 个答案:

答案 0 :(得分:0)

尝试将其传递给本地人,如下所示

<div id="output"></div>
<script src="/js/ejs.min.js"></script>
<script>
  html = ejs.render('<%= people %>', { locals: {people: 'hello'}}); // locals
  document.getElementById('output').innerHTML = html;
</script>

答案 1 :(得分:0)

来晚了,但是我自己解决了这个问题。问题在于,您要由客户端呈现的EJS位于首先由服务器解析的.ejs文件中,因此服务器是抛出错误的服务器,因为它没有读取您的JS来知道{{1 }}是。

对此的快速解决方案是将呈现客户端EJS的代码放在一个外部.js文件中,并将其包括在内。但是我相信您也可以使用people属性将标签从ejs.delimiter更改为类似<% %>的方式,这样,服务器就不会解析该部分代码。 / p>