NodeJS 浏览器将EJS代码呈现为普通HTML文本

k4aesqcs  于 5个月前  发布在  Node.js
关注(0)|答案(1)|浏览(48)

我尝试使用EJS创建一个动态页面,但它并不像模板那样工作,相反,它在浏览器中将EJS代码呈现为普通的HTML文本。
我正要发送数据到这个EJS文件,但当我看了看页面,我得到了我的EJS代码呈现为html文本。
这是一个EJS代码:

<body id="app">

  <form class="container" action="/submit" method="post">
    <div class="horizontal-container">
      <h3>
        Total Score:
        <span id="score">
          <%= locals.totalScore ? totalScore : "0" %>
        </span>
      </h3>

    </div>

    <h1 id="countryFlag">
      <%=question.flag %>
    </h1>
    <div class="answer-container">
      <input type="text" name="answer" id="userInput" placeholder="Name the country" autofocus autocomplete="off">

    </div>
    <button type="submit">SUBMIT<% if(locals.wasCorrect){ %>
        <span class="checkmark">✔</span>
        <% } else if (locals.wasCorrect===false) { %>
          <span class="cross" id="error">✖</span>
          <% } %>
    </button>
  </form>

  <script>
    var wasCorrect = "<%= locals.wasCorrect %>";
    console.log(wasCorrect)
    if (wasCorrect === "false") {
      alert('Game over! Final best score: <%= locals.totalScore %>');
      document.getElementById("app").innerHTML = '<a href="/" class="restart-button">Restart</a>'
    }

  </script>

字符串
这就是我得到的:

current score <%= counter %>
<%= question %>
Enter The Name Of Country ["a input block here"]
SUBMIT<% if(locals.wascorrect){ %> ✔ <% } else if (locals.wascorrect===false) { %> ✖ <% } %>
<% if(locals.wascorrect){ %> <% if(wascorrect == false) { %> <% } %> <% } %>


我该怎么补救?

kwvwclae

kwvwclae1#

您看到的行为是预期的行为。在查看之前,模板首先需要编译为HTML。如果您只是在浏览器中查看模板文件,它将显示未编译的版本。
这是在node.js环境中使用EJS的典型方式:

let template = ejs.compile(str, options);
template(data);
// => Rendered HTML string

ejs.render(str, data, options);
// => Rendered HTML string

ejs.renderFile(filename, data, options, function(err, str){
    // str => Rendered HTML string
});

字符串
您可以尝试EJS CLI来测试您的模板。向其提供模板文件和数据文件,并指定输出文件。

ejs ./template_file.ejs -f data_file.json -o ./output.html


参考网址:https://ejs.co/#docs

相关问题