Node.js/ejs - Using interpolation inside a ejs file with a loop

拥有回忆 提交于 2019-12-11 18:42:56

问题


I have an inline (in the html/ejs) script inside a ejs file and the file is built by node.

homepage.ejs

<html>
  <head>

    <script>
      var i18nRotatingKws = [];
      for (var i=1; i<90; i++) { 
        var i18nRotatingKws[i] = "<%- `rotatingKws.rotatingKw${i}` %>";
      } 
    </script>
  </head>
</html>

The output, after the ejs file is compiled should be:

<html>
  <head>

    <script>
      var i18nRotatingKws = [];          
      var i18nRotatingKws[1] = "<%- rotatingKws.rotatingKw1 %>";
      var i18nRotatingKws[2] = "<%- rotatingKws.rotatingKw2 %>";
      var i18nRotatingKws[3] = "<%- rotatingKws.rotatingKw3 %>";
      var i18nRotatingKws[4] = "<%- rotatingKws.rotatingKw4 %>";
     //and so on until 90
    </script>
  </head>
</html>

Those values, rotatingKws.rotatingKw1, rotatingKws.rotatingKw2...are all defined then in a i18n file (dependent on the language).

I i don't use any loop in the ejs it's perfectly working. It means if I really write 90 lines such as var i18nRotatingKws[1] = "<%- rotatingKws.rotatingKw1 %>";`the build works and I checked on the web page, it works too.

I have a special node.js script that parses the ejs file before tje ejs compiles to change the values from a i18n file like here:

i18n/locales.js

module.exports = {    
  rotatingKws: {
    rotatingKw1: __("rotatingKw1"),
    rotatingKw2: __("rotatingKw2"), 
    rotatingKw3: __("rotatingKw3"),
  },
}

locales/fr.js

module.exports = {  
  //rotatingKws
  "rotatingKw1":"nice keyword1",
  "rotatingKw2":"cool stuff",
  "rotatingKw3":"hip man",
}

The loop is the problem: the build fails and I get the following error:

i is not defined at eval

How to fix this?

来源:https://stackoverflow.com/questions/54786184/node-js-ejs-using-interpolation-inside-a-ejs-file-with-a-loop

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