尝试在我的快递ejs应用程序中渲染html实体

时间:2017-10-01 17:20:07

标签: javascript node.js express ejs

这是我试图呈现的页面

<% include ../partials/boilerplate %>



    <div class="triviaContainer">
        <h1>GAME TIME!!! </h1>
        <% var i =0; data.forEach(question =>{ i+=1 %>

    <div class="questionRow">
        <div> <%= question.question  %></div>
    </div>
    <div class="questionRow1">
        <div  clicked="" id="correctanswer<%=i %>" class="correctAnswer"  > A: <%= question.correct_answer %></div>

        <div clicked="" id="incorrectanswer<%=i %>" class="incorrectanswer<%=i %>" >B: <%= question.incorrect_answers[0].incorrect_answer %></div>
    </div>
    <div class="questionRow2">
        <div clicked="" id="secondincorrectanswer<%=i %>"  >C: <%= question.incorrect_answers[1].incorrect_answer %></div>
        <div clicked="" id="lastanswer<%=i %>" >D: <%= question.incorrect_answers[2].incorrect_answer %></div>
    </div>


     <%   }) %>
<form class="gameForm" method='POST' action='/trivia/score'>

    <input type="hidden" name="points" value="" id="points"/> 
    <input type="hidden" name="gameid" value="<%= data[0].game_id %>"/>
    <input type="hidden" name="questions" value="<%= data[0].number_of_questions %>"/> 
    <input type="submit" value="GET RESULTS">
</form>
       </div>


<script type="text/javascript" src="javascript/triviaGameScript.js"></script>

<% include ../partials/end %>

我在foreach函数的question.question部分中呈现问题。如果你看这个屏幕截图,最后一个问题有一个引用html实体。我有几个问题有这些实体,并希望找到一个npm包来解码它们。 The last question next to the fedex is where the entity is

这是控制器,我需要html-entities npm package

const triviaModel = require('../models/trivia');
const authHelpers = require('../services/auth/auth-helpers')
const Entities = require('html-entities').XmlEntities;
const entities = new Entities();
const triviaapiController = {};

triviaapiController.index = (req, res) => {
console.log(req.body.game_id);
triviaModel.GetGame(req.body.game_id)
    .then(data =>{
          console.log(data);

          res.render('trivia/trivia-index', {
            data: data,
      });
    })
    .catch(err => {
      console.log(err);
      res.status(500).json({ err });
    });
}

琐事指数承诺中的数据部分是存储问题和答案的地方。

这是此特定包的文档。 https://www.npmjs.com/package/html-entities我不确定如何使用它。我应该将它应用于ejs文件,还是应用于传入的数据对象。任何帮助都将非常感谢!

1 个答案:

答案 0 :(得分:1)

你编码使用这样的包:

triviaapiController.index = (req, res) => {
  console.log(req.body.game_id)
  triviaModel.GetGame(req.body.game_id)
    .then(data => {
      console.log(data)
      var decodedData = []
      for (var q of data) {
        var decodedQ = {
          question: entities.decode(q.question),
          correct_answer: q.correct_answer,
          incorrect_answers: q.incorrect_answers
        }
        decodedData.push(decodedQ)
      }

      res.render('trivia/trivia-index', {
        data: decodedData
      })
    })
    .catch(err => {
      console.log(err)
      res.status(500).json({ err})
    })
}