JSRender/JSViews templating engine renders JSON objects as follows:
<div>{{:name}}</div>
This works well for objects like {"name":"Foo","age":"28"}
.
But what if I have a person
object instead (ex. {"person":{"name":"Foo","age":"28"}}
)?
How can I render something like this?
<div id="template">{{:person.name}}</div>
Here's what it looks like with a bit more context:
<div id="container"></div>
<script id="view-event-template" type="text/x-jsrender">
<div id="template">{{:person.name}}</div>
</script>
<script id="view-event-template" type="text/javascript">
$.ajax({
...
success: function (data) {
// returns json object like `{"person":{"name":"Foo","age":"28"}}`
$("#container").html(
$("#template").render(data)
);
}
});
</script>
There is nothing wrong with your example. Did you try it? You are allow to access nested properties.
Please read the documention: https://www.jsviews.com/#paths
const $template = $('#template');
const data = { "person": {"name": "Foo", "age": "28" } };
$('#output').html($template.render(data));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jsrender/1.0.0-beta/jsrender.min.js"></script>
<div id="output"></div>
<script id="template" type="text/x-jsrender">{{:person.name}}</script>