-1

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>
Ryan
  • 14,682
  • 32
  • 106
  • 179
  • Maybe it would be a good idea to remove this question now, since it was a non-issue, so not useful to others wanting to understand rendering object properties in JsRender... – BorisMoore Aug 13 '20 at 23:31

1 Answers1

0

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>
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
  • Ha, there must be something I'm missing. Thanks. I am able to get it to work by rendering the data as an array: `$template.render([data])` and then referencing it as `{{person[0].name}}`. – Ryan Aug 13 '20 at 15:57
  • @Ryan You shouldn't have to wrap the person in an array. The example above works for the provided data. Make sure the data you are passing in is correct. – Mr. Polywhirl Aug 13 '20 at 16:03