Populate Templates Using JavaScript – populator.js

Category: Javascript | May 24, 2021
Author:smeshchankin
Views Total:72 views
Official Page:Go to website
Last Update:May 24, 2021
License:MIT

Preview:

Populate Templates Using JavaScript – populator.js

Description:

populator.js is a JavaScript library that can be used to dynamically populate templates with any data you provide.

How to use it:

1. Include the populator.js on the page.

<script src="populator.js"></script>
2. Populate an HTML form using the populator.js.
<form id="form">
  <h3 class="login-form">Login data</h3>
  <input type="text" id="username" placeholder="Username" value="{{username}}" />
  <input type="password" id="password" placeholder="Password" value="{{password}}" />
  <button type="submit">{{buttonName}}</button>
</form>
populator.populate('#form', {
  username: 'Sergey', 
  password: 'secret', 
  buttonName: 'Sign in'
});

3. Populate an HTML list.

<ul>
  <li class="user">{{id}}. {{login}}</li>
</ul>
const users = [
      { id: 1, login: 'Sergey' },
      { id: 2, login: 'Andrey' },
      { id: 3, login: 'Kirill' },
      { id: 4, login: 'Anton' },
      { id: 5, login: 'Vadim' },
      { id: 6, login: 'Ruslan' },
      { id: 7, login: 'Boris' },
      { id: 8, login: 'Oleg' }
];
populator.populate('.user', users);

4. Populate a template’s attribute:

<table>
  <tr style="height: 50px;">
    <td class="cell" style="width: 50px; background-color: {{color}}">&nbsp;</td>
  </tr>
</table>
const colors = [
      { color: 'red' },
      { color: 'green' },
      { color: 'blue' }
  ];
populator.populate('.cell', colors);

5. Populate from JSON.

<ul data-json="products.json">
  <li class="product">{{id}}. {{name}}</li>
</ul>
populator.populateFromJson();

You Might Be Interested In:


Leave a Reply