0

I'm working on a project in which I would like to import a locally stored HTML template using JavaScript.

This template will be dynamically filled with datas that I get by accessing a website REST API.

This is an example of what I want to do :

index.html :

<!DOCTYPE html>
<html>
<head>
    <title>My Site</title>
</head>
<body>
    <div id="loaded-content">
        <!-- Here will be displayed the template -->
    </div>
</body>
<script type="text/javascript" src="script.js"></script>
</html>

template.html:

<div id="data">
    <h1 id="data-name">value</h1>
    <p id="first-attribute">value</p>
    <p id="first-attribute">value</p>
    <p id="first-attribute">value</p>
</div>

datas.json:

{
    "datas":
    [
        {
            "name": "value",
            "first-attribute": "value",
            "second-attribute": "value",
            "third-attribute": "value"
        },
        {
            "name": "value",
            "first-attribute": "value",
            "second-attribute": "value",
            "third-attribute": "value"  
        }
    ]
}

For each object contained in datas, I want to display the template again.

Currently, I load the template using XMLHttpRequest object. I can display the content of my template but I can't access to the template's DOM to change the value of its elements.

Which method should I use to correctly load my HTML file ? I'm looking for something in pure Javascript (no jQuery or something).

Thank you for your help =)

2 Answers2

0

Your immediate problem is that your template as it currently stands will result in multiple elements with the same ID, which isn't allowed.

If you have control of the template, change it to be a more traditional template style where vars are bracketed off rather than relying on HTML IDs. So I'd change your template to be:

<div>
    <h1>{{name}}</h1>
    <p>{{first-attribute}}</p>
    <p>{{second-attribute}}</p>
    <p>{{third-attribute}}</p>
</div>

This way we can run string replacements via REGEX rather than outputting then interrogating the items by IDs.

Let's say #content is the container element for the templates, data stores your parsed JSON data and template stores the unparsed template string:

var
cntr = document.querySelector('#content'),
html;

//iterate over data items
data.datas.forEach(function(obj) {

    //grab all var references i.e. {{foo}} and replace them with actual values, if exist
    html = template.replace(/\{\{[^\}]+\}\}/g, function(match) {
        var var_name = match.replace(/^\{\{|\}\}$/g, '');
        return obj[var_name] || '??';
    });

    //append the readied HTML to the content container
    cntr.innerHTML += html;
});
Mitya
  • 33,629
  • 9
  • 60
  • 107
  • Thanks for your reply, I will try that ;) For the IDs, that was just an example, a the IDs will be created with the data values. – Anthony Ferry Jan 19 '18 at 15:58
0

This is an example. You can use a JSON parser to get the data in the format you need. So here is what you do: create a dummy <div> DOM element to push later, use replace function to replace val with the value of the data variable. Then finally append this to the HTML's div element. If you got the data using an XMLHttpRequest, pass on the data to template. Then replace the placeholders value with the data from parsing JSON. And use replace method to do so. It should work fine.

var template = document.createElement("div");

var data = "Hello world";

template.innerHTML = "<h1>val</h1>";

template.innerHTML = template.innerHTML.replace("val", data);

document.getElementById("myDiv").appendChild(template);
<div id="myDiv">

</div>
ICanKindOfCode
  • 1,000
  • 1
  • 11
  • 32
  • Thanks for your reply but I'm looking for a solution that doesn't need to write HTML in my javascript code =) But whatever, thank you =) – Anthony Ferry Jan 19 '18 at 15:58
  • You will then need to use Regex. [Don't use Regex to parse HTML](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) – ICanKindOfCode Jan 19 '18 at 16:04