如何访问从后端传入的HTML中的javascript对象的字段名称?

时间:2019-01-16 05:47:53

标签: html node.js express swig-template

示例:

var obj = {name:bob,         }

我不希望访问name的值,即bob,而是访问包含obj键之类的数组,例如[name]。

<h1>{{ pagename|title }}</h1>
<ul>
{% for author in collections %}
  <li >
    {{ author.uno }}
    {{ author.subject }}
    <script>
        var array =  Object.keys(author).map((key) => key) ;  
        document.write('<p>' + array + '</p>');
      </script>


    {% for element in author %}
       <li >
             {{element  }} 


      </li>
    {% endfor %}


  </li>
{% endfor %}
</ul>

此处集合是从后端(即nodejs)传入的对象数组。 作者是一个javascript对象。 我尝试使用脚本标记内的逻辑来获得所需的结果。 但是它没有在网页上打印任何内容。 我还尝试过将{{}}放置在不同的位置,而没有取得丰硕的成果。

1 个答案:

答案 0 :(得分:0)

更新:我忘记了您正在使用swig-template。这是我的建议:

//backend :
const author = { /* author object */ };
author.keys = Object.keys(author).join(', ');
swig.renderFile('/path/to/template.html',{ author });

然后将其放入template.htm;

{{ author.subject }}
{{ author.keys }}
{% for element in author %}
   <li >
         {{element  }} 


  </li>
{% endfor %}