Created
January 3, 2022 00:37
-
-
Save DavesCodeMusings/56ae8f7d129ab8f1aa3862927ef66ec4 to your computer and use it in GitHub Desktop.
Dynamic HTML from JavaScript without a bunch of `html += . . .` madness.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env node | |
| /* | |
| * Dynamic HTML from JavaScript without a bunch of `html += ...` madness. | |
| */ | |
| // Define the HTML with {{ }} placeholders for values to be filled in later. | |
| let template = ` | |
| <details> | |
| <summary><img alt="{{state}}" src="icons/{{stateIcon}}">{{name}}</summary> | |
| <p> | |
| {{id}}<br> | |
| {{createDate}} | |
| {{status}} | |
| </p> | |
| <details> | |
| `; | |
| // Mock up some data like something that may have come from an API call. | |
| let container = { | |
| id: '0123abcd4567efgh', | |
| state: 'running', | |
| name: 'enigmatic_ballyhoo', | |
| createDate: 'Jan 1, 1970', | |
| status: 'Up for 42 days' | |
| } | |
| // Insert some new information based on the data received. | |
| stateIcon = 'stopped.svg'; | |
| if (container.state == 'running') { | |
| container.stateIcon = 'play.svg'; | |
| } | |
| // Fill in the placeholder values. | |
| html = template.replace(/{{\w+}}/g, (match) => { | |
| match = match.replace(/^{{/, '').replace(/}}$/, ''); | |
| return container[match]; | |
| }); | |
| // Display the before and after. | |
| console.log(`\nTemplate:`); | |
| console.log(template); | |
| console.log(`\nAfter replacements:`); | |
| console.log(html); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment