Comparing query string fields to display JSON using JS Render

149 views Asked by At

I have a working JS Render template that pulls in a different JSON file based on the values of a query string. I am trying to figure out how to change the value of the JS Render element (id_1) based off of the query string field "source".

So if my url ends with "?market=ab&source=index", I want "{{:id_1}}" to display "index_id_1" from the ab.JSON file.

HTML

<script type="text/x-jsrender" id="logoTempl">
<div id="cta-div">
    <a href="{{:id_1}}">Button</a>
</div>
</script>
<div class="mainContainer">
</div>

JSON

[{"assets" : {
        "field1" : "value",
        "field2" : "value"
    },
    "ids" : {
        "index": {
            "id_1": "index_id_1",
            "id_2": "index_id_2",
            "id_3": "index_id_3"
        },
            "email": {
                "id_1": "email_id_1",
                "id_2": "email_id_2",
                "id_3": "email_id_3"
            }
        }
    }
]

JS

if (market == 'ab' && source == 'index') {
    $.getJSON('data/ab.json', function(data) {
      var logoField = logo.render(data);
      var id1 = data[0].ids.index.id_1
        $(".mainContainer").html(logoField);
        $("{{:id_1}}").html(id1);
    })
}
1

There are 1 answers

0
BorisMoore On BEST ANSWER

If I understand correctly you want the template to show the value ids[source].id_1.

You can pass in source as a helper, e.g.

...logo.render(data, {idgroup: source});

and then in the template, write:

{{:ids[~idgroup].id_1}}

or you can create a getId helper function, e.g.:

...logo.render(data, {getId: function(index) {
  return data[index].ids[source];
}});

and then in the template, write:

{{:~getId(#index).id_1}}