12

I would like to use a variable from my jsrender template in order to produce a snippet of javascript, but I can't figure out how to place a <script type="text/javascript"> within my <script id="data-item-tpl" type="text/x-jsrender">

Hopefully the below is fairly clear. The below code produces an Uncaught SyntaxError. If I remove the tags from the embedded script, then it is simply printed onto the page as text.

In the code below, I am trying to generate a div with the id 'chartId', and then a script which will fill that div with content, via the MyChart object.

<script id="data-item-tpl" type="text/x-jsrender">
    <div class="item">
        <div class="graphs">
            <ul class="thumbnails">
                {{for graphs}}
                <li><div class="thumbnail"><img src="{{html:url}}" width="190" height="120" /><p>{{html:graphTitle}}<br />{{html:value}}</p></div></li>
                {{/for}}
                <!-- Here we insert both the placeholder for, and the javascript to populate charts -->
                <li><div id="{{html:chartId}}" style="width:120;height:190px;"></div></li>
                <script type="text/javascript">
                    var chartObj = new MyChart("{{html:chartId}}");
                    chartObj.render();
                </script>
            </ul>                           
        </div>
        ...
</script>

1 Answer 1

13

I just did a little playing around and was able to get it working like this:

{{:"<scr" + "ipt type=&quot;text/javascript&quot;>"}}
    var chartObj = new MyChart("{{html:chartId}}");
    chartObj.render();
{{:"</scr" + "ipt>"}}

Maybe not the most elegant solution, but when I put an alert in there, it fired.

2
  • 1
    Yep! That's the kind of code-quality that everyone who writes web code has to live with pretty often. Web technologies suck. Period. Thanks! Jan 3, 2014 at 15:36
  • I am getting "Too many illegal characters" error in watch window. I couldn't use it.
    – Shesha
    May 5, 2016 at 5:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.