How to access field names of javascript object in HTML passed in from backend?

1k views Asked by At

Example:

var obj={name:bob, }

I want to access not the value of name i.e. bob instead an array containing keys of obj like [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>

Here collections is an array of objects passed in from backend i.e. nodejs. Author is a javascript object. I have tried getting desired result using logic inside script tag. But it is not printing anything on webpage. I have also tried placing {{}} at different positions without getting fruitful results.

1

There are 1 answers

2
Kai On

update: I forgot you're using swig-template. Here is my suggestion:

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

and then, put it in template.htm;

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


  </li>
{% endfor %}