0

I have been playing with jquery and templates, and I cobbled together a simple template binding system:

<script type="text/template" id="Template">
    <div>{0}</div>
</script>

and...

var buffer = '';
var template = $("#Template").html();

response.Data.forEach(function(arrayElement)
{
    buffer += template.format(arrayElement.p1,);
});

$("#ListOutput").html(buffer);

My question is: Is there a more natural way that I can take a JSON object, such as:

{"user": { "id": "1","name": "bob" }}

And use a more natural binding sintax, such a this:

<script type="text/template" id="Template">
    <div>{user.name}</div>
</script>

straight JS or jquery would be idea. I know that some of the more complex data binding tools like Angular provide these features, but the complexity of some of the data binding plugins makes my head swim. Anything based on node is right out.

Is there some native feature I don't know about that makes this easy?

1 Answer 1

2

If you can use ES2015 "template strings".

<script type="text/template" id="Template">
    <div>${user.name}</div>
</script>

You have not added response array, so I am assuming it as

[
 {"user": { "id": "1","name": "bob" }},
 {"user": { "id": "2","name": "Some Name" }}
]

var buffer = '';
var template = $("#Template").html();
response.Data.forEach(function(arrayElement) {
    var user = arrayElement.user;
    buffer += eval('`' + template + '`');
});

$("#ListOutput").html(buffer);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.